动态更改图标[QT/c++]
Dynamically changing icon [QT/c++]
我想在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()
....
希望这能帮助。。。
相关文章:
- Qt VTK交互风格的信号到小部件
- QT在错误的班级中寻找空位
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何在Qt窗口小部件中使用QStringView(或QStringRef)
- 如何在Qt C++中更改光标
- 如何在MS Visual Studio 2019中运行QT UI
- QT通过C++添加映射QML项目
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 使用Qt C++计算类似Git的SHA1哈希
- Qt focusObjectChanged example?
- 如何在cpp文件之间切换窗口?在Qt中
- Qt和C++:将QLineEdit添加到QTabWidget中
- 从数据库实时显示QT c++中的数据
- Qt Quick-如何仅从c++代码与qml属性交互
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 如何在Qt中取消捕获字符串
- Qt SQLite没有查询或参数计数不匹配
- Qt SQlite无法创建表