Qt+css绘制标题

之前学过html和小程序,帮老师做项目的时候也用过vue,在想qt绘制界面是不是也可以使用css,然后查了一些资料,绘制了一个标题,准备用到智能家居的上位机上面。

成果

源码

重写了paintEvent函数和TimeEvent函数,一个用于绘制标题,一个用于刷新右边的时间

代码里面的注释比较详细

复制代码
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //可以通过样式表设置背景
    this->setAttribute(Qt::WA_StyledBackground);
   /*
    这行代码为窗口或控件设置了一个样式表,用于定义其外观样式。样式表使用CSS(层叠样式表)语法来描述界面元素的外观。
    background-image: url(:/image/res/head_bg.png); 设置背景图像。这里使用的资源路径可能是一个资源文件或者资源别名,指向一个图片文件。
    background-repeat: no-repeat; 确保背景图像不会重复。
    background-position: center; 设置背景图像居中显示。
    background-attachment: fixed; 这通常用于浏览器背景,确保背景图像固定,不随页面滚动而滚动
    */
    this->setStyleSheet("background-image: url(:/new/prefix1/res/head_bg.png); background-repeat: no-repeat; background-position: center; background-attachment: fixed;");
    //定时器 1s 1s一次刷新
     startTimer(1000);
}
void Widget:: timeEvent(QTimerEvent *){
    //刷新
    update();
}
void Widget:: paintEvent(QPaintEvent *){
    QPainter painter(this);
    //抗锯齿、平滑图像转换和抗锯齿文本
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing); // 抗锯齿和使用平滑转换算法

    painter.setPen(QColor(255, 255, 255));
    QFont font = this->font();
    font.setPixelSize(42);
    painter.setFont(font);
    //居中
    painter.drawText(rect(), Qt::AlignCenter, "智能家居控制平台");

    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString formattedDateTime = currentDateTime.toString("yyyy年M月d日 hh:mm:ss");
    //半透明的白色(alpha值为140,即70%不透明度
    painter.setPen(QColor(255, 255, 255, 140));
    font.setPixelSize(18);
    painter.setFont(font);
    //右对齐
    painter.drawText(rect().marginsRemoved(QMargins(10, 10, 10, 10)), Qt::AlignVCenter | Qt::AlignRight, formattedDateTime);
}
相关推荐
AAA阿giao3 小时前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
掘金安东尼14 小时前
用 CSS 打造完美的饼图
前端·css
掘金安东尼21 小时前
纯 CSS 实现弹性文字效果
前端·css
前端Hardy1 天前
HTML&CSS&JS:打造丝滑的3D彩纸飘落特效
前端·javascript·css
前端Hardy1 天前
HTML&CSS&JS:丝滑无卡顿的明暗主题切换
javascript·css·html
parade岁月2 天前
Tailwind CSS v4 — 当框架猜不透你的心思
前端·css
前端Hardy2 天前
HTML&CSS&JS:基于定位的实时天气卡片
javascript·css·html
程序员阿耶2 天前
5 个让 CSS 起飞的新特性,设计师看了直呼内行
css
前端Hardy2 天前
HTML&CSS:纯CSS实现随机转盘抽奖机——无JS,全靠现代CSS黑科技!
css·html
漂流瓶jz3 天前
BEM、OOCSS、SMACSS、ITCSS、AMCSS、SUITCSS:CSS命名规范简介
前端·css·代码规范