Qt样式表可以创建非常专业美观的界面,本篇文章重点去介绍如何与组件的属性相互配合使用。
1,创建一个新的工程,完成如下界面。
2,加入样式表
/*添加样式和鼠标感应*/
QPushButton
{
color:white;
background-color:#27a9e3;
border-width:0 px;
border-radius:3px;
}
QPushButton:hover{
color:white;
background-color:#66c011;
border-width:0px;
border-radius:3px;
}
QPushButton:pressed{
color:white;
background-color:yellow;
border-width:0px;
border-radius:3px;
}
至此,我们完成样式表的制作,
更进一步搭建样式表与c++之间的桥梁。
QPushButton[pagematches=true]
{
color:white;
background-color:red;
border-width:0 px;
border-radius:3px;
}
注意:这里放到第二块,否则效果不理想。
如果QPushButton的pagematches属性返回true,那么将设置新的样式。但是默认是没有这个属性的,所以我们要自定义一个。使用 Qobject::setProperty();命令。
在mainwindow.cpp中
#include <QStyle>
ui->setUi(this);
ui->button1->setProperty("pagematches",true);
设置按钮的属性,并默认为true,所以是红色
在tabwidget上右键添加slot函数
void MainWindow::on_tabWidget_currentChanged(int index)
{//默认是false
ui->pushButton->setProperty("pagematches",false);
ui->pushButton_2->setProperty("pagematches",false);
ui->pushButton_3->setProperty("pagematches",false);
//设置一个为使用中
if(index==1)
{
ui->pushButton->setProperty("pagematches",true);
}else if(index==2)
{
ui->pushButton_2->setProperty("pagematches",true);
}else
{
ui->pushButton_3->setProperty("pagematches",true);
}
//更新按钮样式
ui->pushButton->style()->polish(ui->pushButton);
ui->pushButton_2->style()->polish(ui->pushButton_2);
ui->pushButton_3->style()->polish(ui->pushButton_3);
}
这样就添加了侦听,当tabwidget切换的时候,会自动选择相应的按钮。
在QT中可以自由得为任何widget组件添加自定义属性。当定义某些条件下,修改组件的属性时,自定义属性非常有用,扩展了 QT的功能。我们不仅可以设定setProperty函数,也可以读取函数比如:QObject::property();
面对比较复杂的部件,有很多子组件组成,那么可以在QT中灵活的进行指定子控制。通过部件的类名加上子组件的名字就可以进行具体的控制。中间使用双冒号链接比如修改滑块的下按钮:
QSpinBox::down-button
{
image:url(:/image/spindown.png);
subcontrol-origin:padding;
subcontrol-position:right bottom;
}
//只对子组件 down-button起作用