动态更改图标[QT/c++]

Dynamically changing icon [QT/c++]

本文关键字:c++ QT 图标 动态      更新时间:2023-10-16

我想在Qt中实现一个动态变化的性能托盘图标。然而,我似乎在谷歌上找不到任何相关的链接,所以你知道如何做到这一点吗?

如果你不知道我在问什么,我已经创建了一个gif文件,你会在那里得到我的想法。

因此,任何链接、代码和示例都值得赞赏。http://gifninja.com/animatedgifs/715636/icon.gif

编辑

所以我想出了一些代码,但它不起作用,你能看看吗?

主窗口.h

QPixmap test;
QSystemTrayIcon *speedPerformance;

mainwindow.cpp

然后在主窗口构造函数中我有:

this->test = QPixmap(16,16);

然后我称这段代码为:

QTimer *trayIconTimer = new QTimer(this);
connect(trayIconTimer , SIGNAL(timeout()), this, SLOT(updateSpeedIcon()));
trayIconTimer->start(2000); // update it every 2 seconds

然后我创建trayicon

speedPerformance = new QSystemTrayIcon(this);
QPainter p(&test);
QColor color;
p.fillRect(0,0,16,16,color.black());
p.end();
speedPerformance->setIcon(QIcon(test));

最后,这里是updateSpeeIcon()的代码,每2秒调用一次:

QPainter p(&test);
QColor color;
p.setPen(color.red());
xPaint+=3;
qDebug() << xPaint;
p.fillRect(xPaint,0,2,16,color.red());
p.end();
speedPerformance->setIcon(QIcon(test));

所以,除了当我试图通过点击安装的其他trayicon退出程序时,这段代码会给我带来分段错误之外,结果托盘图标是16x16黑色正方形,而且我从来没有试图画那些红色填充的矩形,你知道有什么错吗?

一个可能的解决方案是使用QTimer。您必须将timeout信号与一个插槽连接,以便更新图标。

QTimer *trayIconTimer = new QTimer(this);
connect(trayIconTimer , SIGNAL(timeout()), this, SLOT(updateTrayIcon()));
timer->start(2000); // update it every 2 seconds

在您的插槽中,您将创建新图标并设置它:

voi updateTrayIcon()
{
     QIcon newIcon = CreateIcon();
     // I assume that tray is a pointer to the `QSystemTrayIcon` 
     tray->setIcon(newIcon);
}

由于您有一个托盘图标,您一定已经使用了QSystemTrayIcon类。使用此类,您可以随时更改托盘图标。只需拨打QSystemTrayIcon::setIcon()即可。

如果我正确理解了你的问题,以下是你应该遵循的步骤;

inside your application class,
    create a icon variable
    create a dataSource variable
    inside constructor()
        icon = DEFAULT_ICON
        connect(dataSource, SIGNAL(performanceChanged()), 
                 this, SLOT(updateIcon()));
    inside updateIcon()
        var = dataSource.getPerformanceLevel();
        switch(var)
            case LEVEL_1:
                icon = getLevel1Icon()
            case LEVEL_2:
                icon = getLevel2Icon()
            ....

希望这能帮助。。。