如何使按钮立即禁用? [英] How to make push button immediately disabled?

查看:43
本文介绍了如何使按钮立即禁用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


大家好!我在 QPushButton 实例上发现了一些奇怪的东西.哦,首先,我正在使用..


Hello everyone! I've found something strange on QPushButton instance. Oh, first of all, I am using..

  • Windows 7
  • python 3.4
  • PyQt5

我的测试代码是...

# coding: utf-8

import sys, time
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.targetBtn = QPushButton('target', self)
        self.targetBtn.move(100, 100)
        self.targetBtn.clicked.connect(self.sleep5sec)

        self.setGeometry(100, 100, 300, 300)
        self.show()

    def sleep5sec(self):
        self.targetBtn.setEnabled(False)
        time.sleep(5)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

我想要的是......当用户按下目标按钮时,该按钮立即禁用.但是在我的代码中,目标按钮在 sleep(5) 后被禁用.

What I want is.. when a user push the target button, the button immediately disabled. But in my code, target button is disabled after sleep(5).

我的代码有什么问题?

感谢您阅读我的问题!请帮忙!

Thank you for reading my question! Please help!

推荐答案

thread 我在评论中链接了@MichalF,python 的 sleep 完全冻结了 UI,因此它不会让 .setEnabled 方法更新.

As suggested in the thread I linked in the comment and @MichalF, python's sleep completely freezes the UI, so it does not let the .setEnabled method to be updated.

在 Qt 中,所有事件都由 UI 的主线程(它是另一个工作线程)管理,因此,像 .setEnabled 这样的操作在 UI 中不会立即生效(需要一些时间来重新绘制它).使用 time.sleep 会冻结 UI 线程,因此 Qt 的主工作线程在计时器结束之前不会更新(重绘)UI.

In Qt all events are managed with the UI's main thread (which is another worker) and thus, actions like .setEnabled have no immediate effect in the UI (takes a bit to repaint it). Using time.sleep the UI threads freeze and thus, the Qt's main worker doesn't update (repaint) de UI until the timer is ended.

改变它的一种方法是使用 PyQt5.QtCore.QTimer:

A way to change it is by using PyQt5.QtCore.QTimer:

def sleep5sec(self):
    self.targetBtn.setEnabled(False)
    QTimer.singleShot(5000, lambda: self.targetBtn.setDisabled(False))

上面的例子会立即禁用 targetBtn 并在 5 秒后重新启用它.

The above example would instantly disable targetBtn and after 5 second it will re-enable it again.

这篇关于如何使按钮立即禁用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆