Qt Style Sheets(qt样式表)

我认为qt样式表对于专注于ui交互的人,其在qt的地位不亚于信号与槽的地位。通过qt样式表可以展示绝大部分你可以想象得到的风格。

qt样式表的使用是先将要特例化的样式建立在后缀qss的文件中,在程序启动时加载进来,那些在qss文件中涉及的样式将会替换掉qt各个界面元件默认的样式。

要将qss加载在程序中,需要3个步骤:

1)在qt资源文件.qrc中加入的qss资源,例如:

<RCC version="1.0">
    <qresource prefix="/">
        <file>qss/skin.qss</file>
    </qresource>

</RCC>

2)在程序中读取qss文件信息并设置,示例:

//设置界面皮肤
bool setSkin(QApplication* const app, QString const &skinFile)
{
    QFile file(skinFile);
    if (QFile::exists(skinFile) && file.open(QIODevice::ReadOnly))
    {
        //设置默认风格,有Windows WindowsXP WindowsVista Motif CDE Plastique Cleanlooks多种选择
        QApplication::setStyle(QStyleFactory::create("WindowsXP"));
        QString strTemp;
        QTextStream in(&file);
        while (!in.atEnd())
        {
            strTemp.append(in.readLine());
        }
        file.close();
        app->setStyleSheet(strTemp);
    } else{
        return false;
    }
    return true;
};

//主函数入口
int main(int argc, char *argv[])
{
    //app构造
    QApplication app(argc, argv);
    //主窗口
    MainWindow w;
    //设置界面皮肤
    setSkin(&app ,":/qss/skin.qss");
    w.show();
    return app.exec();
};

3)在qss中将需要变更样式的元件进行重新设计,例如要改变qtreeview的风格

/******************      QTreeView       **************/
QTreeView {
    /*alternate-background-color: yellow;*/
    font-size:12px;
    font-family:"Courier New";
    show-decoration-selected: 1;
}

QTreeView::item {
    border: 1px solid #d9d9d9;
    border-top-color: transparent;
    border-bottom-color: transparent;
}
/* 鼠标在QTreeView上面移动时的效果 */
QTreeView::item:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
    border: 1px solid #bfcde4;
    /*background-color:rgba(0,230,230,127);*/
}

QTreeView::item:selected {
    border: 1px solid #0055ff;
    /*background-color:rgba(0,230,0,127);*/
}
/* 节点被选中激活时的效果 */
QTreeView::item:selected:active{
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0028ff, stop: 1 #0055ff);
}

QTreeView::item:selected:!active {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0000ff, stop: 1 #0028ff);
}

QTreeView::branch:has-siblings:!adjoins-item {
    border-image: url(:/images/vline.png)0;
}

QTreeView::branch:has-siblings:adjoins-item {
    border-image: url(:/images/branch-more.png)0;
}

QTreeView::branch:!has-children:!has-siblings:adjoins-item {
    border-image: url(:/images/branch-end.png)0;
}

QTreeView::branch:has-children:!has-siblings:closed,
QTreeView::branch:closed:has-children:has-siblings {
    border-image: none;
    image: url(:/images/branch-closed.png);
}

QTreeView::branch:open:has-children:!has-siblings,
QTreeView::branch:open:has-children:has-siblings {
    border-image: none;
    image: url(:/images/branch-open.png);
}

treeview_img:Qt Style Sheets(qt样式表)

关于样式表更多更深层级的知识可参考:http://doc.qt.io/qt-4.8/stylesheet-examples.html

上一篇:Gensim训练*语料库


下一篇:qt on android for PL2303HXD USB to RS232