【问题标题】:Custom style page for qt quick QML aplications (like HTML and CSS)qt quick QML 应用程序的自定义样式页面(如 HTML 和 CSS)
【发布时间】:2015-12-14 18:54:12
【问题描述】:

是否可以在 QT 中创建自定义样式文件并将其应用于所有 QML 文件(就像 CSS 确实适用于 HTML 一样)?

QML 是否有任何“类”声明?

【问题讨论】:

    标签: qt styles qml qtquick2 qtquick-designer


    【解决方案1】:

    如果你想在 QML 中声明一个“类”,你必须创建新的 QML 文件。它的名称必须以大写字母开头。您也可以使用 C++ 创建自定义对象,但这可能不是您想要的。

    假设您要创建自定义 Text 元素,以便文本始终居中并适合给定尺寸。因此,您创建一个名为 CustomText.qml 的文件并编写:

    /* CustomText.qml file */    
    
    import QtQuick 2.0
    
    Text {
        id: customText
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        clip: true
        fontSizeMode: Text.Fit
        font.pixelSize: height
        wrapMode: Text.WordWrap
        minimumPixelSize: 3
        color: "black"
    
        /* using these lines you can set custom font loaded from a file */
    //    font.family: customFont.name
    //    FontLoader {
    //        id: customFont
    //        source: "qrc:/myCustomFont.ttf"
    //    }
    }
    

    现在你可以像这样使用它了:

    /* main.qml file */
    import QtQuick 2.3
    import QtQuick.Window 2.2
    
    Window {
        visible: true
    
        width: 300
        height: 300
    
        Rectangle {
            id: rectangle1
            color: "lightgrey"
            x: 5
            y: 5
            width: 200
            height: 50
    
            CustomText {
                anchors.fill: parent
                text: "testing custom text object"
            }
        }
    
        Rectangle {
            id: rectangle2
            color: "lightgrey"
            anchors.left: rectangle1.left
            anchors.top: rectangle1.bottom
            anchors.topMargin: 5
            width: 50
            height: 50
    
            CustomText {
                anchors.fill: parent
                text: "testing custom text object"
            }
        }
    
        Rectangle {
            id: rectangle3
            color: "lightgrey"
            anchors.left: rectangle2.left
            anchors.top: rectangle2.bottom
            anchors.topMargin: 5
            width: 100
            height: 100
    
            CustomText {
                anchors.fill: parent
                text: "testing custom text object"
            }
        }
    }
    

    这就是它的样子:

    【讨论】:

    • 如果从现在开始,每个元素都必须使用绿色字体颜色。?我必须为每个元素创建一个自定义 QML 吗?我想采用一个现有的项目,并以某种方式改变它的风格
    • @DanielSantos 不幸的是,是的。您必须手动将每个 Text 更改为 CustomText 并在其中设置 color: "green"
    猜你喜欢
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2023-03-29
    相关资源
    最近更新 更多