python - 使 QLabel 可点击

标签 python pyqt click pyqt5 qlabel

我有一个充满 QPixmap 的 Qlabel,我想在这个标签被点击后启动一个进程/功能。我按如下方式扩展了 QLabel 类:

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 函数中,我将标签从

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

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

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

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

应用程序没有崩溃,但标签仍然不可点击。有人可以帮我解决这个问题吗?

最佳答案

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

class QLabel_alterada(QLabel):
    clicked=pyqtSignal()

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

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

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

enter image description here

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

enter image description here

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

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

关于python - 使 QLabel 可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575626/

相关文章:

c++ - 单击路由器 C++ 标准库

WPF MenuItem.Click 在育儿后中断

python - 蒙特卡罗模拟 : Underlying distribution parameter changes during simulation run based on conditions

python - Cloud Scheduler 调用的 GCP Cloud Run 应用程序的当前最大超时是多少

python - 如何将 numpy 数组作为 Catboost Python 中的分类特征传递

python - 如何在树形 View 中显示父目录?

python - 如何在 PyQt TextEdit 中缩进区域

c++ - 大型文本文件查看器如何工作?如何构建大型文本阅读器

java - 是否可以删除 FieldSet 然后重新添加它?如何?

python - scikit-optimize 中 cv_results_ 和 best_score_ 中的测试分数是如何计算的?