Qt之加载QSS文件

摘要:
简要描述如何创建新的QSS文件。编写QSS文件。有关更多信息,请参阅创建新的QSS文件。首先,创建一个后缀为qss的文件,例如style。qss,并将其添加到资源文件中。在样式中编写QSS在QSS文件中编写自己的样式代码,例如:QToolTip{border:1pxsolidrgb;background:white;color:black;}加载QSS为了方便将来的调用,您可以编写一个静态加载样式函数:#include#incluseclassCommonHelper{public:staticvoidsetStyle{QFileqss;QSS.open;qApp-˃setStyleSheet;QSS.close();}};然后,加载main函数:int main{QApplication;//加载QSS样式CommonHelper::setStyle;MainWindowwindow;window.show();return a.exec();}很容易找到实施原则。事实证明,qApp是QCoreApplication的单个实例,然后它被转换为QAapplication#Ifdefined#undefqApp#endif#defineqApp1234。那么,为什么Q Application调用setStyleSheet()后,所有零件样式都会发生变化?

http://blog.csdn.net/liang19890820/article/details/51993435

版权声明:进步始于交流,收获源于分享!纯正开源之美,有趣、好玩、靠谱。。。作者:一去丶二三里 博客地址:http://blog.csdn.net/liang19890820

目录(?)[+]

简述

Qt中关于样式的使用很常见,为了降低耦合性(与逻辑代码分离),我们通常会定义一个QSS文件,然后编写各种部件(例如:QLable、QLineEdit、QPushButton)的样式,最后使用QApplication进行样式加载,这样,就可以让整个应用程序就共享同一个样式。

新建QSS文件

首先,新建一个后缀名为qss的文件,例如:style.qss,将其加入资源文件(qrc)中。

提示:也可以使用绝对路径或相对路径。

编写QSS

在style.qss文件中编写自己的样式代码,例如:

QToolTip {
        border:1px solid rgb(45, 45, 45);
        background:white;
        color:black;
}
加载QSS

为了方便以后调用,可以写一个静态加载样式的函数:

#include <QFile>
#include <QApplication>
class CommonHelper
{
public:
    static void setStyle(const QString &style) {
        QFile qss(style);
        qss.open(QFile::ReadOnly);
        qApp->setStyleSheet(qss.readAll());
        qss.close();
    }
};

然后,在主函数里进行加载:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 加载QSS样式
    CommonHelper::setStyle("style.qss");

    MainWindow window;
    window.show();

    return a.exec();
}
实现原理

很容易发现,原来qApp是QCoreApplication的一个单例,然后,将其转换为QApplication。

#if defined(qApp)
#undef qApp
#endif
#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
  • 1
  • 2
  • 3
  • 4

那么,QApplication调用setStyleSheet()以后为何所有的部件样式都改变了呢?

通过逐层分析,我们发现其主要是调用了setStyle():

void QApplication::setStyle(QStyle *style)
{
    if (!style || style == QApplicationPrivate::app_style)
        return;

    QWidgetList all = allWidgets();

    // clean up the old style
    if (QApplicationPrivate::app_style) {
        if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
            for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
                QWidget *w = *it;
                if (!(w->windowType() == Qt::Desktop) &&        // except desktop
                     w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
                    QApplicationPrivate::app_style->unpolish(w);
                }
            }
        }
        QApplicationPrivate::app_style->unpolish(qApp);
    }

    QStyle *old = QApplicationPrivate::app_style; // save

    QApplicationPrivate::overrides_native_style =
        nativeStyleClassName() == QByteArray(style->metaObject()->className());

#ifndef QT_NO_STYLE_STYLESHEET
    if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
        // we have a stylesheet already and a new style is being set
        QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
        style->setParent(newProxy);
        QApplicationPrivate::app_style = newProxy;
    } else
#endif // QT_NO_STYLE_STYLESHEET
        QApplicationPrivate::app_style = style;
    QApplicationPrivate::app_style->setParent(qApp); // take ownership

    // take care of possible palette requirements of certain gui
    // styles. Do it before polishing the application since the style
    // might call QApplication::setPalette() itself
    if (QApplicationPrivate::set_pal) {
        QApplication::setPalette(*QApplicationPrivate::set_pal);
    } else if (QApplicationPrivate::sys_pal) {
        clearSystemPalette();
        initSystemPalette();
        QApplicationPrivate::initializeWidgetPaletteHash();
        QApplicationPrivate::initializeWidgetFontHash();
        QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
    } else if (!QApplicationPrivate::sys_pal) {
        // Initialize the sys_pal if it hasn't happened yet...
        QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
    }

    // initialize the application with the new style
    QApplicationPrivate::app_style->polish(qApp);

    // re-polish existing widgets if necessary
    if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
        for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
            QWidget *w = *it;
            if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
                if (w->style() == QApplicationPrivate::app_style)
                    QApplicationPrivate::app_style->polish(w);                // repolish
#ifndef QT_NO_STYLE_STYLESHEET
                else
                    w->setStyleSheet(w->styleSheet()); // touch
#endif
            }
        }

        for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
            QWidget *w = *it;
            if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
                    QEvent e(QEvent::StyleChange);
                    QApplication::sendEvent(w, &e);
                    w->update();
            }
        }
    }

#ifndef QT_NO_STYLE_STYLESHEET
    if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
        oldProxy->deref();
    } else
#endif
    if (old && old->parent() == qApp) {
        delete old;
    }

    if (QApplicationPrivate::focus_widget) {
        QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
        QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
        QApplicationPrivate::focus_widget->update();
    }
}
Qt之加载QSS文件第1张

主要分为4步:

  1. 清理旧样式 - unpolish()
  2. 初始化新样式 - polish()
  3. 加载新样式 - polish() + sendEvent()、update()
  4. 删除旧样式 - delete

通过调用QWidgetList all = allWidgets()获取了所有控件的集合,然后,利用迭代器QWidgetList::ConstIterator对每一个控件进行处理,最后,通过QApplication::sendEvent()来发送QEvent::StyleChange事件,达到全局样式更改。

免责声明:文章转载自《Qt之加载QSS文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇一个被遗忘的ccflow工作流引擎自定义表单开发模式正则表达式---用户验证下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

python爬取图片遇见src乱码: data:image/png;base64

Python抓取图像并遇到src乱码:data:image/png;Base64会抓取您喜欢的图像,但图像的src在抓取的代码中出现了乱码:data:image/png;base64.)“”头1,编码=字符串。splitdata=b64decodedwithopenasf:f.写入。close()注意:我还没有成功。。。。。。...

解决less 版本过高

执行npminstall--无保存加载器。安装less后,在样式中使用less时将报告错误。这是由于less loader版本过高造成的。您可以在package.json中查看less的当前版本。因此,在这种情况下,我们可以先卸载现有的less loader,然后安装less loader的较低版本npmuninstallless loader...

influxdb简单使用

之前对influxdb有一个简单的了解和入门的使用,近期由于想使用influxdb做一点东西玩玩,又要捡起influxdb。而在influxdb下没有细分的表的概念,influxdb下的表在插入数据库的时候自动会创建。更多用户权限设置可以参看官方文档:https://docs.influxdata.com/influxdb/v1.0/query_langua...

爱快路由器的一些注意事项硬件配置+多线负载均衡

以下数据仅供参考:注意:磁带载体的数量因使用环境和带宽大小的不同而不同。此外,请注意32位系统的安装。最大内存为4G,最大内存为3G-----硬盘------安装“爱快路由”时对硬盘的最低要求为1G以上。...

【转】MUD教程--巫师入门教程4

在MUD中,为了解决定时触发某种现象,一般有两种方法,一种是通过call_out()延时呼叫,另一种就是通过心跳。于是,对于要跨起离线前后的象做牢这类的事,大多都是采用condition。附:由于大多数MUD里的心跳是每两秒调一次,5+random是5至14次,因此可以看出每一个condition被调用的时间是平均19秒。然后它会按照condition的名字...

k8s集群上删除pod及service

删除k8s集群中的pod:找到pod的名称空间,并根据名称空间删除pod1。首先删除pod2,然后删除相应的部署。否则,删除pod是无用的。您还将看到pod,因为deployment.yaml文件中定义的副本数如下:delete the pod[root@test2~]#kubectlgetpod-njenkinsNAMEREADYSTATUSRESTART...