Add a click on QLineEdit

笑着哭i 提交于 2019-12-01 11:10:47

Just simply call the MainWindow mousePressEvent and give it the event variable the line edit received

class MyLineEdit(QtGui.QLineEdit):

    def __init__(self, parent):

        super(MyLineEdit, self).__init__(parent)
        self.parentWindow = parent

    def mousePressEvent(self, event):
        print 'forwarding to the main window'
        self.parentWindow.mousePressEvent(event)

Or you can connect a signal from the line edit

class MyLineEdit(QtGui.QLineEdit):

    mousePressed = QtCore.pyqtProperty(QtGui.QMouseEvent)

    def __init__(self, value):

        super(MyLineEdit, self).__init__(value)

    def mousePressEvent(self, event):
        print 'forwarding to the main window'
        self.mousePressed.emit(event)

Then just connect the signal in your main window where you created it

    self.tc = MyLineEdit(self.field[con.ConfigFields.VALUE])#self.tc = wx.TextCtrl(self.parent, -1, str(field[con.ConfigFields.VALUE]), pos=(x+220, y-3), size=(200, -1))
    self.tc.mousePressed[QtGui.QMouseEvent].connect(self.mousePressEvent)

I use the following to connect any method as the callback for a click event:

class ClickableLineEdit(QLineEdit):
    clicked = pyqtSignal() # signal when the text entry is left clicked

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton: self.clicked.emit()
        else: super().mousePressEvent(event)

To use:

textbox = ClickableLineEdit('Default text')
textbox.clicked.connect(someMethod)

Specifically for the op:

self.tc = ClickableLineEdit(self.field[con.ConfigFields.VALUE])
self.tc.clicked.connect(self.mouseseleted)

This is what I used to do onClick for QLineEdits

class MyLineEdit(QtGui.QLineEdit):

    def focusInEvent(self, e):
        try:
            self.CallBack(*self.CallBackArgs)
        except AttributeError:
            pass
        super().focusInEvent(e)

    def SetCallBack(self, callBack):
        self.CallBack = callBack
        self.IsCallBack = True
        self.CallBackArgs = []

    def SetCallBackArgs(self, args):
        self.CallBackArgs = args

and in my MainGUI:

class MainGUI(..):

    def __init__(...):
        ....
        self.input = MyLineEdit()
        self.input.SetCallBack(self.Test)
        self.input.SetCallBackArgs(['value', 'test'])
        ...

    def Test(self, value, test):
        print('in Test', value, test)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!