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);//显示关闭状态
}

效果图:

相关推荐
小冯的编程学习之路19 分钟前
【软件测试】:推荐一些接口与自动化测试学习练习网站(API测试与自动化学习全攻略)
c++·selenium·测试工具·jmeter·自动化·测试用例·postman
chxii1 小时前
5java集合框架
java·开发语言
老衲有点帅1 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈2 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
IsPrisoner2 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
猪八戒1.02 小时前
C++ 回调函数和Lambda表达式
c++
Python私教2 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust
chicpopoo2 小时前
Python打卡DAY25
开发语言·python
源远流长jerry2 小时前
匿名函数lambda、STL与正则表达式
c++