在 qml Qt 中设置样式

Setting the Style in qml Qt

我想在 qml 中为我的元素设置样式。为此,我想使用像 Material 样式这样的样式。使用可在以下位置找到的示例:

https://doc.qt.io/qt-5/qtquickcontrols2-material.html

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12

ApplicationWindow {
   visible: true

   Material.theme: Material.Dark
   Material.accent: Material.Purple

   Column {
       anchors.centerIn: parent

       RadioButton { text: qsTr("Small") }
       RadioButton { text: qsTr("Medium");  checked: true }
       RadioButton { text: qsTr("Large") }
     }
}

给我所附图片中看到的结果。 无论我使用哪种风格,都没有改变。

我目前在 Windows 10 Os.

下使用最新的免费 Qt 版本

谁能帮帮我? 是否可以在 QML 中简单地全局覆盖样式并创建自己的样式。

您还必须从 C++ 设置样式。看到这个 Qt documentation.

所以在你的主要添加QQuickStyle::setStyle("Material");

正如 the docs 指出的:

To run an application with the Material style, see Using Styles in Qt Quick Controls.

在Qt Quick Controls 2中有几种设置样式的方法:

  1. Using QQuickStyle in C++:

    • 在您的 .pro 中添加 QT += quickcontrols2 并在 main.cpp
    • 中使用 #include <QQuickStyle>QQuickStyle::setStyle("Material");
  2. Command line argument:

    • 您可以通过添加参数从 console/CMD 运行:./your_executable -style material.
    • 如果您使用 Qt Creator,您可以转到项目-> 构建 & 运行-> 运行 并在命令行参数中添加:-style material.

  1. Environment variable:

    • 您可以 运行 来自 console/CMD:QT_QUICK_CONTROLS_STYLE=material ./your_executable
    • 如果您使用的是 Qt Creator,您可以在项目-> 构建 & 运行-> 运行-> 运行 环境部分添加它。

    • 或在main.cpp中添加qputenv("QT_QUICK_CONTROLS_STYLE", "material");
  2. Configuration file:

    必须创建 qtquickcontrols2.conf 文件:

    [Controls]
    Style=Material
    

    并且必须在 qresource 中:

    <RCC>
        <qresource prefix="/">
            <file>main.qml</file>
            <file>qtquickcontrols2.conf</file>
        </qresource>
    </RCC>