1.在代码特定位置插入样式:
this->setStyleSheet(
"QPushButton#btn_one,QPushButton#btn_two{
background-color:yellow;//设置背景色
font-family:SimSun;//设置字体
color:black;//设置字体颜色
border:1px solid black;//设置边框
border-radius:5px;//设置按钮四角为圆角(特定设置:border-top-left-radius:8px;)
}"
"QPushButton:hover{
background-color:red;
}"//设置鼠标移到按钮上的样式
"QPushButton:pressed{
background-color:blue;
padding-left:10px;
padding-right:10px;
padding-top:10px;
padding-bottom:10px;
}"
);//this为当前类
ui.widget->setStyleSheet("background-color:green");//ui.widget为ui界面中的控件
2.利用文件导入Qss样式:
//导入QSS
QString strCss;
QFile qssFile(QString(":/target.css"));//获取文件
if(qssFile.open(QIODevice::ReadOnly))//以只读的方式打开文件
{
strCss = qssFile.readAll();//获取文件中的内容
qssFile.close();//关闭文件
}
//设置QSS样式
this->setStyleSheet(strCss);
附加:
1.this->setStyleSheet("QPushButton#btn1:hover,QPushButton#btn2:hover{backGround-color:rgb(69,179,229);}");如果要对多个按钮设置鼠标覆盖效果必须要在每个按钮后面加上:hover,
2.如果需要对界面和界面内的控件设置QSS的话,应该将两个样式分开写。如果合在一块写会造成控件的样式失效
比如设置界面的背景色为白色,界面中的按钮背景色为红色
this->setStyleSheet("background-color: white;");
ui.btn->setStyleSheet("QPushButton:hover{background-color:red;}");
而不能这样写:
this->setStyleSheet("background-color: white;");
this->setStyleSheet("QPushButton:hover{background-color:red;}");
第二种写法会直接失效,没有任何效果。最好是用代码写样式,UI设计师设置样式,可能会失效。
---------------------------------------------------------------------------------
尤其是设置父子样式,一定要将父控件对象单独设置样式,还要将子对象单独设置样式,防止父对象的样式覆盖子对象的样式
this->setStyleSheet("QDialog#examDialog{background-color:white;}");
this->setStyleSheet("QPushButton#btn{background-color:blue;}");
3.如果QSS样式失效请检查你在界面是否也写了样式。
4.设置qtableview表头样式,ui.tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{color:black;background-color:black;}");