c++ - 在 Qt 上,如何在运行时更改工具栏中某个 Action 的图标?

标签 c++ qt icons runtime qtoolbar

在计算任意精度数字的程序中。 我在任务栏上有一个 Action 。

QAction* button_stop_continue。

我在程序的开头设置了绿色图标,当执行计算时它应该变成红色等等。

我已经尝试过这样的事情:

connect(this, SIGNAL(startedComputing()), this, SLOT(turnIconRed()));
connect(this, SIGNAL(finishedComputing()), this, SLOT(turnIconGreen()));

函数 turnIconRed 看起来与此类似:

void turnIconRed()
{
    button_stop_continue->setIcon(QIcon("images/red-light.png"));
}

我想出了一些非常丑陋的算法 :S。在 Qt 上没有直接的方法来处理这个问题吗?有什么想法吗?

谢谢。

最佳答案

我会将 QAction 子类化并为其可能存在的状态添加一些逻辑。将某些东西的颜色硬编码到方法的名称中绝不是一个好主意。通过子类化 QAction,封装了它的外观。

这可能是这样的:

头文件:

class StateAction : public QAction
{
    Q_OBJECT
public:
    explicit StateAction(QObject *parent = 0);

public slots:
    void start();
    void stop();
    void pause();
};

执行文件:

StateAction::StateAction(QObject *parent) :
    QAction(parent)
{
    this->stop();
}

void StateAction::start()
{
    this->setIcon(QIcon(":/states/start.png"));
}

void StateAction::stop()
{
    this->setIcon(QIcon(":/states/stop.png"));
}

void StateAction::pause()
{
    this->setIcon(QIcon(":/states/pause.png"));
}

现在,在您的 MainWindow 中,您只需将其插槽连接到正确的信号即可使用该自定义 QAction:

头文件:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

signals:
    void startedComputing();
    void finishedComputing();
    void pausedComputing();

private:
    void createActions();
    void createToolbars();
    void createConnections();
    StateAction *m_stateAction;
};

执行文件:

...

void MainWindow::createConnections()
{
    connect(this, SIGNAL(startedComputing()), m_stateAction, SLOT(start()));
    connect(this, SIGNAL(finishedComputing()), m_stateAction, SLOT(stop()));
    connect(this, SIGNAL(pausedComputing()), m_stateAction, SLOT(pause()));
}

关于c++ - 在 Qt 上,如何在运行时更改工具栏中某个 Action 的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701435/

相关文章:

python - setfill 和 setw python 等效?

qt - 如何使用TCP连接QSqlDatabase? (Qt的MySQL驱动程序)

icons - Twitter Bootstrap 和 Font Awesome 的重复图标问题

java - 单独的小型、大型 JFrame 图标

C++ 术语消歧

c++ - 在给定列和行的字符数组中查找索引?

C++ WINAPI - 绘制无边框的ListView

c++ - 如何使用Qt检查文件夹是否可写

c++ - 如何在 qt4 设计器中创建自定义插槽?

javascript - 如何在 HTML Canvas 上渲染图标字体,尤其是 Material Design 图标字体?