Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

python - Make QLabel clickable

I have a Qlabel filled with QPixmap and I want to start a process/function once this label clicked. I had extended QLabel class as follows:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QLabel_alterada(QLabel):
  clicked=pyqtSignal()
  def __init(self, parent):
    QLabel.__init__(self, QMouseEvent)

  def mousePressEvent(self, ev):
    self.clicked.emit()

Then, in my pyuic5-based .py file (I used QtDesigner to do the layout) after importing the module where I save the extended QLabel class, inside the automatically generated setupui, function I changed my Label from

self.label1=QtWidgets.QLabel(self.centralwidget)

to

self.label1 = QLABEL2.QLabel_alterada(self.centralwidget)

Finally, in the core app Python file where I put all the procedures/classes whetever needed to the application functionality I added

self.ui.label1.clicked.connect(self.dosomestuff) 

The application does not crashes but the labels still not clickable. Can someone give me some help on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I do not understand why you pass QMouseEvent to the parent constructor, you must pass the parent attribute as shown below:

class QLabel_alterada(QLabel):
    clicked=pyqtSignal()

    def mousePressEvent(self, ev):
        self.clicked.emit()

To avoid having problems with imports we can directly promote the widget as shown below:

We place a QLabel and right click and choose Promote to ...:

enter image description here

We get the following dialog and place the QLABEL2.h in header file and QLabel_changed in Promoted class Name, then press Add and Promote

enter image description here

Then we generate the .ui file with the help of pyuic. Obtaining the following structure:

├── main.py
├── QLABEL2.py
└── Ui_main.ui

Obtaining the following structure:

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.clicked.connect(self.dosomestuff) 

    def dosomestuff(self):
        print("click")


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...