Qt6 加载CSS样式 (28)

一、在Qt Designer中直接添加样式

  • 单个显示控件:对需要修改样式的显示控件,右键单击选中“改变样式表...”选项,在弹出的编辑样式表窗口中,添加对应的样式表内容。
  • 整体显示控件:在Qt Designer的对象查看器子窗口中,选择需要修改的局部或整体的对象,右键单击选中“改变样式表...”选项,在弹出的编辑样式表窗口中,添加对应的样式表内容。

二、在代码中添加样式

针对整体或局部显示控件,使用对应的控件对象(整体的控件对象为this指针)调用setStyleSheet("[样式表内容]")函数来实现控件的样式的设置。

ui->pushButton->setStyleSheet("QPushButton{background-color: rgb(225, 225, 225);border:2px groove gray;border-radius:50px;padding:2px 4px;border-style: outset;}"
                                           "QPushButton:hover{background-color:rgb(229, 241, 251); color: black;}"
                                           "QPushButton:pressed{background-color:rgb(204, 228, 247);border-style: inset;}");

    qBtn->setStyleSheet("QPushButton{color:#FFFFFF;background-color: #1D9DFF;border:2px solid #1d9DFF;}"
       "QPushButton:hover{color: #FF6666;background-color: #8EC8FD;border-radius:4px;}"
       "QPushButton:pressed{color: #FFFFFF;background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #3BA0FE, stop:1 #1D9DFF);}");

三 通过读取样式文件来试着样式

  • 首先将需要设置的样式表内容写入对应的.qss或.css文件中,其样式表内容的书写格式与css一致。
/*所有QPushButton都有效*/
QPushButton
{
   border: 2px solid rgb(190,190,190);
   background-color: rgb(255,38,0);
   color:rgb(0,0,0);
}
/*鼠标在QPushButton悬停时生效*/
QPushButton:hover{
    border: 2px solid rgb(60,142,99);
    border-radius: 6px;
    color:#Faab10
}

/*ObjectName为btn_Start、btn_Stop的QPushButton有效*/
/*是ObjectName 不是属性名,可以使用setObjectName函数设置*/
QPushButton#btn_Start{
    border: 2px solid #33FFFF;
    border-radius: 6px;
    color:#FF0000;
    background-color:#FF99CC;
}
  • 将样式表文件作为资源加入到项目中
  • 打开样式表文件,读取文件内容,并将这些内容存储为Qt的QString类型,然后按照方法2的方式调用。其中,打开和读取样式表文件,并将样式表内容存储为QString类型对象的代码如下所示:
QString loadStyleSheet(const QString &sheetName)
{
    QString styleSheet;
    QFile file(sheetName);
    file.open(QFile::ReadOnly);
    if (file.isOpen())
    {
        styleSheet = QLatin1String(file.readAll());
    }
    return styleSheet;
}
static void setStyle(const QString &cssname)
{
    QFile file(cssname);
    file.open(QIODevice::ReadOnly);
    QString css = QLatin1String(file.readAll());
    qApp->setStyleSheet(css);
    file.close();
}

https://blog.csdn.net/weixin_42887343/article/details/123205555
https://blog.csdn.net/chan_qx/article/details/105764850
https://blog.csdn.net/Snow__Sunny/article/details/119205422
https://www.cnblogs.com/ruandahua/p/16020483.html
https://www.jianshu.com/p/4bf2526cc90d

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容