简体   繁体   English

如何在PyQt5中向QLabel添加信号?

[英]How to add signals to a QLabel in PyQt5?

I have the code below for a interactive label in PyQt4 that can be clicked, right clicked and scrolled. 我有下面的代码用于PyQt4中的交互式标签,可以单击,右键单击并滚动。 I am converting the code for PyQt5 and lots of things in my code are right now based on this element. 我正在转换PyQt5的代码,现在代码中的很多事情都基于此元素。

class ExtendedQLabel(QLabel):
    def __init(self, parent):
        super().__init__(parent)

    def mousePressEvent(self, ev):
        if ev.button() == QtCore.Qt.RightButton:
            self.emit(SIGNAL('rightClicked()'))
        else:
            self.emit(SIGNAL('clicked()'))

    def wheelEvent(self, ev):
        self.emit(SIGNAL('scroll(int)'), ev.delta())

How do I make this PyQt5 compatible? 如何使该PyQt5兼容?

Ok, after a lot of things I understood what I was doing wrong: 好吧,经过很多事情,我明白了我做错了什么:

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

class ExtendedQLabel(QLabel):
    def __init(self, parent):
        super().__init__(parent)

    clicked = pyqtSignal()
    rightClicked = pyqtSignal()

    def mousePressEvent(self, ev):
        if ev.button() == Qt.RightButton:
            self.rightClicked.emit()
        else:
            self.clicked.emit()

if __name__ == '__main__':
    app = QApplication([])
    eql = ExtendedQLabel()
    eql.clicked.connect(lambda: print('clicked'))
    eql.rightClicked.connect(lambda: print('rightClicked'))
    eql.show()
    app.exec_()

In the line with the text clicked = pyqtSignal() and rightClicked = pyqtSignal() what ties those signals to that class that makes the code above work? 在带有文本clicked = pyqtSignal()rightClicked = pyqtSignal() ,这些信号与使上述代码正常工作的类有什么联系? Well the answer is the correct indentation , correct indentation will nest the variable to the class instead of randomly creating a variable that has no use. 答案是正确的缩进 ,正确的缩进会将变量嵌套在类中,而不是随机创建没有用的变量。 It took me a lot of time to perceive this, so thought lefting this here could be useful if someone google this. 我花了很多时间来理解这一点,因此,如果有人用谷歌搜索此内容,请将其遗忘在此处可能会很有用。

from PyQt5 import QtGui,QtCore,QtWidgets

class Clickable_Label(QtWidgets.QLabel):

    def __init__(self):
        super().__init__()
    clicked = QtCore.pyqtSignal()  # signal when the text entry is left clicked

    def mousePressEvent(self, event):
        self.clicked.emit()
        QtWidgets.QLabel.mousePressEvent(self, event)

myLabel=Clickable_Label()
myLabel.setText("Clickable_Label")
myLabel.board_rule_download.clicked.connect(lambda: print('clicked'))`enter code here`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM