【问题标题】:Dynamically changing icon [QT/c++]动态改变图标 [QT/c++]
【发布时间】:2012-03-22 13:29:51
【问题描述】:

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

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

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

编辑

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

ma​​inwindow.h

QPixmap test;
QSystemTrayIcon *speedPerformance;

ma​​inwindow.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

然后我创建托盘图标

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));

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

【问题讨论】:

    标签: c++ qt dynamic icons


    【解决方案1】:

    一个可能的解决方案是使用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);
    }
    

    【讨论】:

    • 好吧,当我想到它时,我得出了相同的结论,但现在我不得不以编程方式创建和绘制图标,这可能会很痛苦。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果我正确理解了您的问题,这些是您应该遵循的步骤;

      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()
                  ....
      

      希望这会有所帮助...

      【讨论】:

      • 嗨,这看起来很不错,但我有很多性能水平......我正在测量打字速度,它可以从 0 到最高 200。 ://
      • 那么,然后编写一个函数来计算性能的颜色值(RGB)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2020-09-11
      • 2014-02-14
      • 1970-01-01
      相关资源
      最近更新 更多