【问题标题】:How to program dynamically a button created with PyQt?如何动态编程使用 PyQt 创建的按钮?
【发布时间】:2016-03-08 13:21:04
【问题描述】:

所以我有一个名为 RunButton 的按钮。当我按下它时,我希望它在 10 秒范围内达到 3 秒标记时将按钮的背景颜色从红色更改为绿色。我就是这样做的:

self.RunButton.clicked.connect(self.run)

def run(self):
    for i in range(10):
        i += 1
        print i
        time.sleep(1)
        if (i == 3):
            self.B18.setStyleSheet("background-color: green")

虽然,当我单击 RunButton 时,它会打印经过的时间,但按钮 B18 仅在 for 循环结束时更改颜色,即 10 秒后,它应该在 3 后更改。

那么我应该如何在循环中更改颜色呢?

【问题讨论】:

    标签: python qt pyqt


    【解决方案1】:

    首先,当你阻塞主线程时,不能有 ui 更新。

    使用 QApplication::processEvents()(它来自 c++,但在 python 中应该是相同的)应该可以帮助你。

    另一件事是,您可以创建一个QTimer 来触发像这样的重新着色(伪代码,不保证有效):

    #class initialisation
    self.timer = QTimer()
    self.timer.setInterval(3)
    self.timer.setSingleShot(True)
    
    self.timer.timeout.connect(lambda x: self.B18.setStyleSheet("background-color: green"))
    self.RunButton.clicked.connect(self.timer.start)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2016-04-05
      • 2013-02-17
      • 2012-02-14
      • 2016-04-28
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多