【问题标题】:PyQt4 QSpinBox.selectAll() not working as expectedPyQt4 QSpinBox.selectAll() 没有按预期工作
【发布时间】:2010-12-25 21:25:02
【问题描述】:

Python 2.5.4 PyQt4

我将 QDoubleSpinBox 子类化为在 focusIn 事件上发出信号:



#Custom widgets for DPL GUI
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

class DPLDoubleSpinBox(QDoubleSpinBox):

    __pyqtSignals__ = ("valueChanged(double)", "focusIn()")

    def __init__(self, *args):
        QDoubleSpinBox.__init__(self, *args)

    def event(self, event):
        if(event.type()==QEvent.FocusIn):
            self.emit(SIGNAL("focusIn()"))
            #self.clear() Works as expected
            self.selectAll() #See below                  

        return QDoubleSpinBox.event(self, event)

if __name__ == "__main__":

    import sys

    app = QApplication(sys.argv)
    widget = DPLDoubleSpinBox()
    widget2 = DPLDoubleSpinBox()
    widget.show()
    widget2.show()
    sys.exit(app.exec_())

如果您在一个框内单击,然后关闭另一个窗口,它会起作用。如果您单击一个内部,然后单击另一个,然后将焦点放在桌面上的任何其他窗口上,它似乎可以工作。

我认为这是一个焦点问题,但无法追踪。我只需要它在单击时全选。我尝试通过它的行编辑指针来做,但我得到了相同的结果。尝试将焦点强制到其他小部件,但结果仍然相同。

您可以连接自定义插槽以在它发出“focusIn()”时触发。然后,您可以使用任何 QSpinBox.selectAll(),它可以工作,只是不能在其自身上工作。

【问题讨论】:

    标签: pyqt4 selectall


    【解决方案1】:

    根据this,在覆盖的focusInEvent 中对selectAll 进行QTimer.singleShot 调用,然后奇迹发生了。

    class SpinBox(QSpinBox):
        def focusInEvent(self, event: QFocusEvent) -> None:
            QTimer.singleShot(0, self.selectAll)
    

    或者像这样(不推荐):

    b = QSpinBox()
    b.focusInEvent = lambda _: QTimer.singleShot(0, b.selectAll)
    

    【讨论】:

      【解决方案2】:

      我知道这个问题已经有两年多了,但由于它是谷歌搜索“qspinbox select on focus”时的第一个结果,我想为后代留下一个解决方案。

      问题在于 QSpinBox.lineEdit() 的行为。使用focusInEvent,您可以调用selectAll(),但由于某种原因,QLineEdit 的mousePressEvent 在焦点事件之后立即清除选择。请参阅here 了解说明。

      解决方案是为 QSpinBox.lineEdit() 小部件或子类 QLineEdit 安装事件过滤器并调用 QSpinBox.setLineEdit()。无论哪种方式,link above 都会向您展示如何通过保留布尔标志并过滤 focusInEvent 和 mousePressEvent 来实现所需的行为。

      【讨论】:

        【解决方案3】:

        我把活动改成了QEvent.Enter

        现在它将self.selectAll()

        我可以侥幸解决这个问题,因为它是针对触摸屏应用程序的,因此用户不会明显看出有什么问题。我仍然很想知道我错过了什么,或者这只是一个错误。

        【讨论】:

          猜你喜欢
          • 2021-10-19
          • 2020-03-18
          • 2012-06-14
          • 2014-11-15
          • 1970-01-01
          • 2012-07-02
          • 2011-09-07
          • 2013-03-03
          • 2015-05-18
          相关资源
          最近更新 更多