Qt C++ QStatusbar 显示表示状态的图片

1、前言

在C++ Qt编程中默认主窗口MainWindow底下自带控件QStatusbar,很多情况下都使用其显示程序的连接状态或开关状态,因为时常需要将图片设置为圆形显示,所以这里记录一下常用的设置的代码,方便以后复制粘贴。

2、封装设置状态的函数

(1)使用遮罩将图片设置成圆形

cpp 复制代码
QPixmap Utils::createCircularPixmap(const QPixmap &src, int diameter)
{
    // 创建一个圆形的 QBitmap
    QBitmap mask(diameter, diameter);
    mask.fill(Qt::color0);

    QPainter painter(&mask);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(Qt::color1);
    painter.drawEllipse(0, 0, diameter, diameter);
    painter.end();

    // 创建一个新的 QPixmap
    QPixmap circularPixmap(diameter, diameter);
    circularPixmap.fill(Qt::transparent);

    painter.begin(&circularPixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QPainterPath pathTemp;
    pathTemp.addEllipse(0, 0, diameter, diameter);
    painter.setClipPath(pathTemp);
    painter.drawPixmap(0, 0, diameter, diameter, src);
    painter.end();

    // 应用圆形遮罩
    circularPixmap.setMask(mask);

    return circularPixmap;
}

(2)调整大小并显示在QStatusbar中

cpp 复制代码
void Utils::statusbarSetPixmap(QStatusBar *statusbar, QString pixPath)
{
    QLabel *lastLabel = statusbar->findChild<QLabel *>(statusbar->objectName()+"_pixLabel");
    if(lastLabel != nullptr){
        delete lastLabel;
    }

    int statusbarSize = 30;//状态栏的大小,圆的直径?
    QLabel *imageLabel = new QLabel(/*qobject_cast<QWidget*>(*/statusbar/*->parent())*/);
    imageLabel->setFixedSize(statusbarSize, statusbarSize);
    imageLabel->setObjectName(statusbar->objectName()+"_pixLabel");

    QPixmap pixmap(pixPath);
    QPixmap pixmap2 = pixmap.scaled(statusbarSize, statusbarSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    imageLabel->setPixmap(Utils::createCircularPixmap(pixmap2, statusbarSize));

    statusbar->addWidget(imageLabel);
}

3、调用

举例两张图片:

调用,这里以http服务器是否开启为例子:

cpp 复制代码
if(httpServerIsOpen){
    Utils::statusbarSetPixmap(ui->statusbar, httpTrueImg);//显示开启状态
}else{
    Utils::statusbarSetPixmap(ui->statusbar, httpFalseImg);//显示关闭状态
}

效果图:

相关推荐
消失的旧时光-19432 小时前
C 语言如何实现“面向对象”?—— 从 struct + 函数指针,到 Linux 内核设计思想
linux·c语言·开发语言
handler012 小时前
滑动窗口(同向双指针)算法:模板与例题解析
c语言·c++·笔记·算法·蓝桥杯·双指针·滑动窗口
Brilliantwxx2 小时前
【算法题】基础计算器的不同实现方式
c++·算法
Sunsets_Red2 小时前
P12375 「LAOI-12」MST? 题解
c++·算法·洛谷·信息学·oier·洛谷题解
小短腿的代码世界3 小时前
Qt时间日期处理与QTimer高级应用:从毫秒级精度到跨平台定时器的完整架构解析
开发语言·qt·架构
TAN-90°-3 小时前
Java 6——成员变量初始值 object equals和== toString instanceof 参数传递问题
java·开发语言
雪度娃娃3 小时前
多用户任务管理器
c++·个人开发
mmz12073 小时前
深度优先搜索DFS3(c++)
c++·算法·深度优先
故事和你913 小时前
洛谷-【图论2-1】树6
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
被AI抢饭碗的人3 小时前
C++过渡Python
开发语言·python