gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:24:31 25 4
gpt4 key购买 nike

在计算任意精度数字的程序中。我在任务栏上有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com