-->

mouseDoubleClickEvent with QLineEdit

2020-07-31 20:36发布

问题:

How can I have a QLineEdit unabled by default but that becomes enabled when receives a mouseDoubleClickEvent()?

How can I implement the mouseDoubleClickEvent()?

I always get the error "not enough arguments" when I try something like:

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

回答1:

You can not set that event with the statement:

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

There are 2 possible options:

  1. The first is to inherit from 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. Install an event filter:

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_())