简体   繁体   中英

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. I am converting the code for PyQt5 and lots of things in my code are right now based on this element.

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?

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? 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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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