【问题标题】:GUI issue with QLineEditQLineEdit 的 GUI 问题
【发布时间】:2018-03-08 11:58:59
【问题描述】:

我有包含许多 QLineEdit 的 GUI,我希望用户再次访问它以修改他的输入时将其清除,我在设计中使用 PyQt5,在脚本中使用 python 3,这里需要什么信号?

【问题讨论】:

    标签: python-3.x pyqt5


    【解决方案1】:

    解决方案是继承 QLineEdit 并覆盖其 focusInEvent 方法以在行编辑获得焦点时发出信号。然后将该信号连接到清除行编辑的方法。

    这是一个例子:

    class GUITest(QtWidgets.QWidget):
    
        def __init__(self):
            QtWidgets.QWidget.__init__(self)
    
            self.layout = QtWidgets.QGridLayout()
    
            self.line_edit = CustomLineEdit()
            self.line_edit_two = CustomLineEdit()
    
            self.line_edit.focus_in.connect(lambda: self.clear_line_edit(self.line_edit))
            self.line_edit_two.focus_in.connect(lambda: self.clear_line_edit(self.line_edit_two))
    
            self.layout.addWidget(self.line_edit)
            self.layout.addWidget(self.line_edit_two)
    
            self.setLayout(self.layout)
    
        def clear_line_edit(self, line_edit):
            line_edit.clear()
    
    
    class CustomLineEdit(QtWidgets.QLineEdit):
    
        focus_in = QtCore.pyqtSignal()
    
        def __init__(self):
            super().__init__()
    
        def focusInEvent(self, QFocusEvent):
            self.focus_in.emit()
    

    【讨论】:

    • 其实我是用Qt设计器来生成Gui的,不是直接把我的小部件放到脚本里
    • 这种方法仍然有效。唯一的区别是您需要告诉 Qt Designer 将小部件提升到自定义类。网上有几个关于如何做到这一点的教程。
    • 请帮助我查找 Qt 设计器的自定义类提升教程
    • 谢谢,它说的很清楚,但我也遇到了一些我无法理解的错误,请你帮我......
    • 这与您上面提出的问题无关。通过错误快速判断并且没有看到任何代码,看起来您在 self.__init__ 不接受任何参数时提供了一个参数。这是另一个问题的问题。不过,在就该错误提出另一个问题之前,我建议您阅读How to ask a good question.
    【解决方案2】:

    我找到了我的答案here,下面的代码只是将点击信号添加到任何小部件,不支持点击事件(我在此处的 QlineEdit 中使用它)

    import sys
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    
    def clickable(widget):
    
        class Filter(QObject):
    
            clicked = pyqtSignal()
    
            def eventFilter(self, obj, event):
    
                if obj == widget:
                    if event.type() == QEvent.MouseButtonRelease:
                        if obj.rect().contains(event.pos()):
                            self.clicked.emit()
                            # The developer can opt for .emit(obj) to get the object within the slot.
                            return True
    
                return False
    
        filter = Filter(widget)
        widget.installEventFilter(filter)
        return filter.clicked
    

    【讨论】:

    • 以链接为主要部分的答案是不够的,因为如果链接断开会使您的答案无法使用,我建议发布链接内容中最重要的部分。阅读How to Answer
    • 我很高兴这不是一个链接,并且您已经对其进行了编辑,但您应该详细说明问题究竟是什么以及您是如何解决的。
    • 只是QLineEdit没有点击信号,所以上面的脚本添加了点击事件
    • 答案在 wiki python 上:wiki.python.org/moin/PyQt/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多