如何在运行时更改工具栏中的动作图标?

 收藏

我想在单击工具栏时更改QAction的图标。

I have seen the same question in C++, but it's hard to me to understand other languages. (On Qt, how to change the icon of an action in the toolbar at runtime?)

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.PausePlay = QAction(QIcon('Play.png'), 'Play')
        self.PausePlay.setCheckable(True)
        self.PausePlay.triggered[bool].connect(self.Playing)

        self.toolbar = self.addToolBar('tb')
        self.toolbar.addAction(self.PausePlay)

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

    def Playing(self, active):
        if active:
            # setting new icon
        else:
            # setting new icon


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MWindow = MainWindow()
    sys.exit(app.exec_())
回复
  • 史安莲 回复

    其他答案表明,没有必要使用QToolButton。在这种情况下,您只应获取QAction并设置一个新图标

    def Playing(self, active):
        self.PausePlay.setIcon(QIcon("icon1.png") if active else QIcon("icon2.png"))