QT5样式表使用归纳总结

1、设置控件为圆角

border-radius: 10px;   //10px表示圆角幅度,值越大角越圆。
2、设置颜色半透明,此处以设置背景颜色举例,其他颜色设置也可参考。

background-color: rgba(89, 108, 94, 80%);     //其中80%为透明度,也可用0~255表示,0为完全透明。

3、设置按键不同状态的样式:

QPushButton:enabled   //设置按键使能时样式
{
    //按键样式
}

QPushButton:disabled   //设置按键未使能时样式
{
    //按键样式
}

QPushButton:pressed   //设置按键按下时样式
{
    //按键样式
}

QPushButton:hover     //设置鼠标悬停在按键上时样式
{
    //按键样式
}

QPushButton:focus    //设置焦点在按键上时样式
{
    //按键样式
}

4、使设置控件的样式对其子控件不生效。

#frame  //使设置的样式只对名为frame的控件生效
{
	border-image: url(:/new/prefix1/pictures/天气背景图.png);
}

6、设置背景颜色background-color时,有时候会不生效,必须设置一下border边框属性才能生效,比如:

background-color: rgb(71, 212, 255);
border: 2px solid gray;
border-radius: 10px;

7、设置Widget背景图片。

若Widget作为最外层父控件时,则不能通过UI设计师页面右键设置样式表来设置其背景图片了,需要通过代码实现。

#include <QPalette>   //添加头文件

//在UI构造函数里添加
 QPalette palette;    
 QPixmap pic("./picture/bg.png");
 palette.setBrush(QPalette::Background, QBrush(pic.scaled(this->size())));//scaled使背景图适应窗口大小
 this->setPalette(palette);

若要使背景图随着窗口大小变化而变化,重写resizeEvent(QResizeEvent *event)函数即可。

8、通过代码设置样式表。

几乎所有控件都包含setStyleSheet这个接口,通过该接口可以设置控件的样式,如下所示。

QString style_sheet_cmd = "border-image: url(:/new/prefix1/pictures/test.png";
ui->frame->setStyleSheet(style_sheet_cmd);

下面几个是对QT样式表归纳的比较详细的博客,供大家参考:

https://www.cnblogs.com/lsgxeva/p/7816938.html

https://www.cnblogs.com/lifan3a/articles/8441175.html

https://blog.csdn.net/qq_31073871/article/details/79943093

猜你喜欢

转载自blog.csdn.net/fangye945a/article/details/84961360