我有一个充满 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 ...
:
我们得到以下对话框并将QLABEL2.h
放在头文件中,将QLabel_changed
放在Promoted class Name中,然后按Add and Promote
然后我们在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/