要在 PyQt5 中实现 QLineEdit 的点击事件,您可以使用 mousePressEvent 或者 eventFilter 方法。

使用 mousePressEvent:

from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget

class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)
        
    def mousePressEvent(self, event):
        print('QLineEdit clicked')
        super(MyLineEdit, self).mousePressEvent(event)
        
if __name__ == '__main__':
    app = QApplication([])
    widget = QWidget()
    line_edit = MyLineEdit(widget)
    widget.show()
    app.exec_()

使用 eventFilter:

from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget

class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)
        self.installEventFilter(self)
    
    def eventFilter(self, widget, event):
        if event.type() == QEvent.MouseButtonPress:
            print('QLineEdit clicked')
        return super(MyLineEdit, self).eventFilter(widget, event)
        
if __name__ == '__main__':
    app = QApplication([])
    widget = QWidget()
    line_edit = MyLineEdit(widget)
    widget.show()
    app.exec_()

请注意,如果您在 MyLineEdit 类中使用 eventFilter 方法,请确保将其安装为事件过滤器。

PyQt5 QLineEdit 点击事件实现方法 - 使用 mousePressEvent 和 eventFilter

原文地址: https://www.cveoy.top/t/topic/m9lW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录