大家都知道很多控件是没有clicked信号的,我在网上找了很多终于总结出2个方法来实现类似需求,比如给QLineEdit添加clicked信号,这样的话,当点击输入框时就会发送clicked信号,其它控件也是一样的做法,如下:
方法1:创建一个继承自QLineEdit的类,然后重写mousePressEvent。
1
2
3
4
5
|
class MyLineEdit(QLineEdit): clicked = pyqtSignal() def mouseReleaseEvent( self , QMouseEvent): if QMouseEvent.button() = = Qt.LeftButton: self .clicked.emit() |
方法2:重写eventFilter事件也可以达到类似的效果。
1
2
3
4
5
6
7
8
9
|
def eventFilter( self , widget, event): if widget = = self .edit: if event. type () = = QEvent.FocusOut: pass elif event. type () = = QEvent.FocusIn: self .clicked.emit() #当焦点再次落到edit输入框时,发送clicked信号出去 else : pass return False |
test.py
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
42
43
44
45
46
|
from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys #方法1 class mylineedit(QLineEdit): clicked = pyqtSignal() #定义clicked信号 def mouseReleaseEvent( self , QMouseEvent): if QMouseEvent.button() = = Qt.LeftButton: self .clicked.emit() #发送clicked信号 class Wind(QDialog): clicked = pyqtSignal() def __init__( self ): super ().__init__() self .lnd = mylineedit() self .edit = QLineEdit() self .edit.installEventFilter( self ) #方法2(1) vb = QVBoxLayout() vb.addWidget( self .lnd) vb.addWidget( self .edit) self .setLayout(vb) self .lnd.clicked.connect( self .showData) self .clicked.connect( self .showData) #该clicked信号是W1的信号而非edit的信号,但可以实现焦点落到edit时触发信号 # 方法2(2) def eventFilter( self , widget, event): if widget = = self .edit: if event. type () = = QEvent.FocusOut: pass elif event. type () = = QEvent.FocusIn: self .clicked.emit() #当焦点再次落到edit输入框时,发送clicked信号出去 else : pass return False def showData( self ): print ( 'ok' ) if __name__ = = "__main__" : app = QApplication(sys.argv) w = Wind() w.show() sys.exit(app.exec_()) |
以上这篇PyQt5实现QLineEdit添加clicked信号的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/sylgdxsgx/article/details/78517015