Implement ClickableLabel With PyQt4

本篇用 PyQt4 实现自定义 ClickableLabel,即当鼠标左键双击Label时,就会触发clicked()信号,然后响应槽函数。文中主要讲解如何用 PyQt4 实现自定义信号。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
"""
A clickable label implemented with PyQt4
"""
class ClickableLabel(QLabel):
"""
clicked signal definition
"""
clicked = pyqtSignal()
def __init__(self, text = "", parent = None):
super(ClickableLabel, self).__init__(text, parent)
self.setText(text)
self.clicked.connect(self.onClicked)
def onClicked(self):
text = self.text()
text = "<center><font color=red>" + text + "</font></center>"
self.setText(text)
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
self.clicked.emit()
if __name__ == "__main__":
app = QApplication(sys.argv)
label = ClickableLabel("Click Me")
label.resize(240, 50)
label.setWindowTitle("Clickable Label")
label.show()
sys.exit(app.exec_())

解析

定义 ClickableLabel

1
2
3
4
5
6
class ClickableLabel(QLabel):
"""
clicked signal definition
"""
clicked = pyqtSignal() # 定义 clicked() 信号,此处无参数

首先定义 ClickabelLabel 类继承 QLabel,并定义信号 clicked()。

构造函数

1
2
3
4
5
def __init__(self, text = "", parent = None):
super(ClickableLabel, self).__init__(text, parent)
self.setText(text)
self.clicked.connect(self.onClicked)

构造函数中实现 ClickableLabel 的文本设置并将自定义信号clicked()与槽函数onClicked()连接起来。

clicked() 信号

1
2
3
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
self.clicked.emit()

重载 mouseDoubleClickEvent() 方法,当鼠标左键双击 ClickabelLabel 构件时,触发 clicked() 信号。

槽函数

1
2
3
4
def onClicked(self):
text = self.text()
text = "<center><font color=red>" + text + "</font></center>"
self.setText(text)

onClicked() 槽函数,将文本的内容设置为红色并置中。