Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyQt QToolButton在焦点时不更新图标_Python_Pyqt_Pyqt5_Qtoolbutton - Fatal编程技术网

Python PyQt QToolButton在焦点时不更新图标

Python PyQt QToolButton在焦点时不更新图标,python,pyqt,pyqt5,qtoolbutton,Python,Pyqt,Pyqt5,Qtoolbutton,使用QToolButton更新按钮集的图标时遇到问题。这个想法是使用电影播放器的按钮。要播放,按下按钮,图标变为暂停。再次按下时,播放暂停,图标恢复为播放。我有一些工作代码,但问题是图标更新不一致。如果我将Qt窗口保持在焦点位置,则需要按下一两个按钮才能将图标更改为预期图像,此时实际图像不是预期图像(交换的播放/暂停) 下面是一些简单的示例代码: from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QStyle, QTo

使用
QToolButton
更新按钮集的图标时遇到问题。这个想法是使用电影播放器的按钮。要播放,按下按钮,图标变为暂停。再次按下时,播放暂停,图标恢复为播放。我有一些工作代码,但问题是图标更新不一致。如果我将Qt窗口保持在焦点位置,则需要按下一两个按钮才能将图标更改为预期图像,此时实际图像不是预期图像(交换的播放/暂停)

下面是一些简单的示例代码:

from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QStyle, QToolButton

class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.play_button = QToolButton(clicked=self.update_button)
        self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.addWidget(self.play_button)

        self.button_pressed = False

    def update_button(self):
        if self.button_pressed:
            self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
            self.button_pressed = False
            print("Button should be set to PLAY. Press is", self.button_pressed)
        else:
            self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
            self.button_pressed = True
            print("Button should be set to PAUSE. Press is", self.button_pressed)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
在上面的例子中,我从一个停止图标开始,只是为了确保观察到一个变化(任何点击都会改变图标)。保持窗口聚焦,我得到以下输出:

  • 第一次单击:“按钮应设置为暂停。按下为真”(图标无变化)
  • 第二次单击:“按钮应设置为播放。按下为假”(图标更改为暂停)
  • 第三次单击:“按钮应设置为暂停。按下为真”(图标更改为播放) (以此类推,按预期继续交换)
我还注意到,如果每次单击后,我在Qt窗口外单击,或者调整Qt窗口的大小,按钮图标将更新为正确的图标。我做错了什么?如何强制更新图标


这种行为主要发生在
QToolButton
上,但
QPushButton
也会产生问题(聚焦时有效,但如果我调整Qt窗口的大小,则行为不当/无法跟踪正确的状态)。在macOS上使用PyQt 5.12.3和qt 5.12.5。

这个问题似乎是macOS的qt实现中的一个错误。我测试了PyQt5和PySide2,所以它必须来自Qt。在
.setIcon()
之后通过调用
.repaint()
强制重画似乎可以解决问题:

self.play_按钮.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.play_按钮.重新绘制()

我看不到Linux中Python 3.8.1和PyQt5 5.14.1的问题,我看不到Windows中Python 3.7.3和PyQt5 5.12.1的问题感谢您的尝试。我担心这会是macOS下PyQt的又一个烦恼。。。