QT全局所有QSS样式实时切换

news/2025/2/9 1:41:21 标签: qt, 数据库, 开发语言

方法如下:

void loadQss(int qssType)
{
    QString name;
    if (qssType == 1)
        name = ":/qss/day.qss";
    else
        name = ":/qss/night.qss";
    QFile file(name);
    file.open(QFile::ReadOnly);
    QString qss;
    qss = file.readAll();
    qApp->setStyleSheet(qss);
    file.close();
}

为什么qApp->setStyleSheet(qss);可以做到全局所有样式实时切换,我来看下setStyleSheet的源码。

void QApplication::setStyleSheet(const QString& styleSheet)
{
    //将样式内容保存到内存,以备候用
    QApplicationPrivate::styleSheet = styleSheet;
    //获取当前应用程序的样式
    QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
    //第一个判断条件:如果传入样式为空,则保持当前应该用程序样式
    if (styleSheet.isEmpty()) { // application style sheet removed
        if (!proxy)
            return; // there was no stylesheet before
        setStyle(proxy->base);
    //如果应用程序已经设置了样式,则只是刷新样式,而不会使用函数传入的样式。
    //这也就告诉我们,为qApp设置样式前,需要卸载当前样式,之后安装样式才能生效
    } else if (proxy) { // style sheet update, just repolish
        proxy->repolish(qApp);
   //当前qApp没有样式,设置我们传进来的样式
    } else { // stylesheet set the first time
        QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
        QApplicationPrivate::app_style->setParent(newProxy);
        setStyle(newProxy);
    }
}
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();
    }
}

通过以上源码我们能看出在qApp的setStyleSheet中会拿到所有控件,清除旧的样式,然后加载新的样式,做到全局所有控件样式的动态切换。


http://www.niftyadmin.cn/n/5845442.html

相关文章

6 maven工具的使用、maven项目中使用日志

文章目录 前言一、maven&#xff1a;一款管理和构建java项目的工具1 基本概念2 maven的安装与配置&#xff08;1&#xff09;maven的安装&#xff08;2&#xff09;IDEA集成Maven配置当前项目工程设置 maven全局设置 &#xff08;3&#xff09;创建一个maven项目 3 pom.xml文件…

多数据源配置及使用,在同一个方法下切换数据源。

切换数据源方法&#xff1a; 1. 通过注解切换数据源&#xff0c;可以在方法上使用也可以在类上使用&#xff0c;遵循就近原则 DS(“数据源名”) 注意&#xff1a;在同一个方法使用多个数据源不要使用Transactional&#xff0c;会导致报错。 2. 方法中手动切换 切换数据源类…

Excel 融合 deepseek

效果展示 代码实现 Function QhBaiDuYunAIReq(question, _Optional Authorization "Bearer ", _Optional Qhurl "https://qianfan.baidubce.com/v2/chat/completions")Dim XMLHTTP As ObjectDim url As Stringurl Qhurl 这里替换为你实际的URLDim postD…

PostGIS:使用shp2pgsql、pgsql2shp、OGR2OGR函数进行数据导入、导出

数据导入与导出函数 数据库数据导入与导出可以通过多个函数完成&#xff0c;QGIS文档介绍了3个函数&#xff1a; shp2pgsql、pgsql2shp、OGR2OGR&#xff0c;分别用于shp导入数据库、数据库文件导出为shp、数据转换为多种数据格式。 &#xff08;1&#xff09;shp2pgsql 在l…

zephyr devicetree

Syntax and structure — Zephyr Project Documentation Input files There are four types of devicetree input files: sources (.dts) includes (.dtsi) overlays (.overlay) bindings (.yaml) The devicetree files inside the zephyr directory look like this: …

65.棋盘 C#例子 WPF例子

这是一个不具备任何功能的UI设计&#xff0c;使用矩形和边界和文字块。通过这些可以自由的创建不同显示效果的内容。 棋盘展示&#xff1a; 代码展示&#xff1a; <Window x:Class"棋盘设计.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xam…

02.07 TCP服务器与客户端的搭建

一.思维导图 二.使用动态协议包实现服务器与客户端 1. 协议包的结构定义 首先&#xff0c;是协议包的结构定义。在两段代码中&#xff0c;pack_t结构体都被用来表示协议包&#xff1a; typedef struct Pack {int size; // 记录整个协议包的实际大小enum Type type; …

STM32G474--Whetstone程序移植(单精度)笔记

1 准备基本工程代码 参考这篇笔记从我的仓库中选择合适的基本工程&#xff0c;进行程序移植。这里我用的是stm32g474的基本工程。 使用git clone一个指定文件或者目录 2 移植程序 2.1 修改Whetstone.c 主要修改原本变量定义的类型&#xff0c;以及函数接口全部更换为单精度…