我试图切换QAction的图标。它取决于特定表的上下文。实际上,每当我启动message.cpp时它都在工作,但是当我在message.cpp上时它不会改变。如果我点击m_action4,我希望updateIcon()
会更改我的图标,但它不会。我可以重新拍摄QAction吗?
首先,我在标题上设置变量:
message.h:
private:
QAction *m_action4;
以下是我的源代码: 的 message.cpp:
QSqlQuery query0;
m_action4 = new QAction(QIcon(":/images/silent1.png"), tr("Mute"), this);
m_muteActive = false;
query0.prepare("SELECT state FROM mute_state WHERE p_id=?");
query0.addBindValue(m_pid);
query0.exec();
if (query0.next() && query0.value(0) == "1" )
{
{
m_muteActive = true;
m_action4->setIcon(QIcon(":/images/speaker.png"));
}
}
m_actionBar->addButton(m_action4);
connect(m_action4, SIGNAL(triggered()), this, SLOT(muteMessages()));
muteMessages()
{
QSqlQuery query;
query.prepare("UPDATE mute_state SET state=? , duration= ? , type=? WHERE p_id=?");
if (m_muteActive)
{
query.addBindValue("0");
query.addBindValue("0");
m_muteActive = false;
}
else
{
query.addBindValue("1");
query.addBindValue("525949");
m_muteActive = true;
}
query.addBindValue("private");
query.addBindValue(m_id);
if (query.exec())
qDebug()<<"query was executed";
}
QTimer::singleShot(100 , this, SLOT(updateIcon()));
}
updateIcon()
{
if (m_muteActive)
m_action4->setIcon(QIcon(":/images/silent1.png"));
else
m_action4->setIcon(QIcon(":/images/speaker.png"));
}
答案 0 :(得分:0)
您发布的代码运行正常。在删除不需要演示它的SQL查询之后,它就在这里:
#include <QApplication>
#include <QAction>
#include <QToolBar>
#include <QGridLayout>
#include <QPainter>
class Ui : public QWidget {
QGridLayout m_grid;
QToolBar m_actionBar;
QIcon m_silent, m_speaker;
QAction m_action4;
bool m_muteActive;
QPixmap drawText(const char * text, int size = 64) {
QPixmap pix(size, size);
QPainter p(&pix);
p.setFont(QFont("helvetica", size*0.8));
p.fillRect(pix.rect(), Qt::white);
p.drawText(pix.rect(), QString::fromUtf8(text));
return pix;
}
public:
Ui() :
m_grid(this),
m_silent(drawText("")),
m_speaker(drawText("")),
m_action4(tr("Mute"), this),
m_muteActive(false)
{
m_grid.addWidget(&m_actionBar, 0, 0);
m_actionBar.addAction(&m_action4);
connect(&m_action4, &QAction::triggered, this, &Ui::muteMessages);
updateIcon();
}
Q_SLOT void muteMessages() {
m_muteActive = !m_muteActive;
updateIcon();
}
Q_SLOT void updateIcon() {
m_action4.setIcon(m_muteActive ? m_silent : m_speaker);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Ui ui;
ui.show();
return a.exec();
}