使 QLabel 可点击

Make QLabel clickable(使 QLabel 可点击)

本文介绍了使 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 mousePressEvent(self, ev):
        self.clicked.emit()

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

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

我们放置一个QLabel并右键单击并选择Promote to ...:

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

我们得到以下对话框,将QLABEL2.h放在头文件中,将QLabel_changed放在Promoted class Name中,然后按Add和Promote

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

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

本文标题为:使 QLabel 可点击

基础教程推荐