在QLineEdit上添加点击事件

2 投票
3 回答
10995 浏览
提问于 2025-04-18 18:55

我正在为QLineEdit设置一个点击事件,已经成功做到了。但是我希望在点击QLineEdit时能返回到主窗口,因为我需要主窗口中的数据来进一步处理这些数据。不过我没有成功让它返回,也没有把主窗口设置为父窗口。希望有人能帮我指出问题所在。非常感谢。

MainWindow
{

...


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

...

}


class MyLineEdit(QtGui.QLineEdit):

    def __init__(self, parent=MainWindow):
        super(MyLineEdit, self).__init__(parent)
        #super(CustomQLineEidt, self).__init__()


    def mousePressEvent(self, e):
        self.mouseseleted()

    def mouseseleted(self):
        print "here"
        MainWindow.mousePressEvent

3 个回答

0

这是我在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

然后在我的主界面(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)
5

我用下面的代码来把任何方法连接到点击事件的回调上:

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)

使用方法:

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

特别针对这个问题:

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

只需要简单地调用一下 MainWindowmousePressEvent 方法,并把文本框接收到的 event 变量传给它。

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)

或者,你可以把文本框的一个信号连接起来。

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)

然后在你创建主窗口的地方,把这个信号连接上。

    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)

撰写回答