前提・実現したいこと
PyQt5で画像ラベルとテキストラベルを横に並べ、ペアにしてリストのように表示し、
ラベルペアに対して同じ動作をさせたいと思っております。
具体的には、マウスオーバーしたら色を変え、クリックしたらメッセージを表示する、です。
今回ソースコードのような形で実装したのですが、PyQtを触り始めたばかりで無駄が多いのではないかと思っております。
よりきれいなPyQt向きなコードを教えていただけないでしょうか。
よろしくお願いいたします。
該当のソースコード
python
from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class LabelTest(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # ラベル参照用辞書 self.lbl_dict = dict() # 背景色 tmpWidget = QWidget() self.backGroundColor = tmpWidget.palette().color(QPalette.Window); # 設定 icosize = 16 width = 120 for i in range(10): # 画像 lblImg = QLabel(self) lblImg.setObjectName(str(i)) lblImg.setText( "●" ) #lblImg.setPixmap( QPixmap("D:\\test.ico") ) #16x16 ico lblImg.installEventFilter(self) lblImg.move(0, i*icosize) lblImg.resize(icosize,icosize) # テキスト lblText = QLabel(self) lblText.setObjectName(str(i)) lblText.setText("Text") lblText.installEventFilter(self) lblText.move(icosize, i*icosize) lblText.resize(width-icosize,icosize) # ラベルペアを参照用辞書に追加 self.lbl_dict.setdefault(str(i), (lblImg,lblText)) self.show() def eventFilter(self, object, event): # マウスオーバーしたラベルペアを黄色にする if event.type()== QEvent.Enter: for key, value in self.lbl_dict.items(): if object.objectName() == key: img, lbl = value palette_yellow = QPalette() palette_yellow.setColor(QPalette.Window, Qt.yellow) img.setPalette(palette_yellow) img.setAutoFillBackground(True) lbl.setPalette(palette_yellow) lbl.setAutoFillBackground(True) return True # マウスアウトしたラベルペアを背景色にする elif event.type()== QEvent.Leave: for key, value in self.lbl_dict.items(): if object.objectName() == key: img, lbl = value palette_blue = QPalette() palette_blue.setColor(QPalette.Window, self.backGroundColor ) img.setPalette(palette_blue) img.setAutoFillBackground(True) lbl.setPalette(palette_blue) lbl.setAutoFillBackground(True) return True # クリックしたらメッセージを表示する elif event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: print(object.objectName(), "clicked!") return True return False if __name__== '__main__': app= QApplication(sys.argv) ex= LabelTest() sys.exit(app.exec_())
まだ回答がついていません
会員登録して回答してみよう