mouseDoubleClickEvent 与 QLineEdit

mouseDoubleClickEvent with QLineEdit

如何让 QLineEdit 默认情况下不可用,但在收到 mouseDoubleClickEvent() 时启用?

如何实施 mouseDoubleClickEvent()

当我尝试类似这样的操作时,我总是会收到错误 "not enough arguments":

if self.MyQLineEdit.mouseDoubleClickEvent() == True:
    do something

您不能使用以下语句设置该事件:

if self.MyQLineEdit.mouseDoubleClickEvent () == True:

有 2 个可能的选项:

  1. 首先是继承自QLineEdit:

import sys

from PyQt4 import QtGui

class LineEdit(QtGui.QLineEdit):
    def mouseDoubleClickEvent(self, event):
        print("pos: ", event.pos())
        # do something

class Widget(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        le = LineEdit()
        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(le)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
  1. 安装事件过滤器:

import sys

from PyQt4 import QtGui, QtCore

class Widget(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self.le = QtGui.QLineEdit()        
        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(self.le)

        self.le.installEventFilter(self)

    def eventFilter(self, watched, event):
        if watched == self.le and event.type() == QtCore.QEvent.MouseButtonDblClick:
            print("pos: ", event.pos())
            # do something
        return QtGui.QWidget.eventFilter(self, watched, event)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())