使用PyQt5使QLabel可点击 [英] make QLabel clickable using PyQt5

查看:2277
本文介绍了使用PyQt5使QLabel可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用QPixmap填充的Qlabel,单击此标签后,我想启动一个进程/功能。我对QLabel类进行了如下扩展:

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()

然后,在基于pyuic5的.py文件(我使用QtDesigner进行布局)中,将模块导入到我保存扩展的QLabel类的模块中,并在自动生成的setupui函数内部更改了我的标签

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)

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

最后,在核心应用python文件中,我将所有程序/我添加的应用程序功能所需要的所有类

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?

预先感谢

推荐答案

我不明白为什么要将QMouseEvent传递给父构造函数,必须按如下所示传递parent属性:

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 __init__(self, parent=None):
        QLabel.__init__(self, parent)

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

为避免出现问题导入后,我们可以直接促销小部件,如下所示:

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

我们放置 QLabel 并右键单击并选择升级到...

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

我们得到以下对话框,并将 QLABEL2.h 放在头文件和 QL中升级类名称中的abel_changed ,然后按添加并升级

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

然后我们在pyuic的帮助下生成.ui文件。获得以下结构:

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

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

获得以下结构:

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_())

这篇关于使用PyQt5使QLabel可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆