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

效果图:

相关推荐
CodeCraft Studio29 分钟前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html
QQ_43766431430 分钟前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
aramae31 分钟前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
封奚泽优1 小时前
使用Python实现单词记忆软件
开发语言·python·random·qpushbutton·qtwidgets·qtcore·qtgui
liulilittle2 小时前
C++/CLI与标准C++的语法差异(一)
开发语言·c++·.net·cli·clr·托管·原生
daixin88482 小时前
什么是缓存雪崩?缓存击穿?缓存穿透?分别如何解决?什么是缓存预热?
java·开发语言·redis·缓存
小狄同学呀2 小时前
VS插件报错,g++却完美编译?API调用错因分析
c++
程序员编程指南2 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
你我约定有三2 小时前
RabbitMQ--消息丢失问题及解决
java·开发语言·分布式·后端·rabbitmq·ruby
小乖兽技术2 小时前
C#与C++交互开发系列(二十四):WinForms 应用中嵌入C++ 原生窗体
c++·c#·交互