QML - Cannot assign to non-existent property “style”

独自空忆成欢 提交于 2020-07-18 09:07:54

问题


I'm using Qt 5.10.1 with Qt Creator 4.5.1 and the style property is never available in elements.

For example, as shown here ButtonStyle QML Type , I would like to do:

Button {
    text: "A button"
    style: ButtonStyle {...}
}

But, I get the error:

Cannot assign to non-existent property "style"

I tried with a rectangle, progressbar and I get the same error.

Edit #1:

I do have all these imports. If the import was missing, I would get the error on ButtonStyle , but the error is on style.

import QtQuick 2.2
import QtQuick.Controls 2.3
import QtQuick.Dialogs 1.0
import QtGraphicalEffects 1.0
import QtQuick.Shapes 1.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Styles 1.4

回答1:


There are 2 types of Buttons in QML:

  • Button Qt Quick Controls 2: https://doc.qt.io/qt-5.10/qml-qtquick-controls2-button.html
  • Button Qt Quick Controls: http://doc.qt.io/qt-5/qml-qtquick-controls-button.html

In your case, you are importing the Qt QuickControls 2 Button: import QtQuick.Controls 2.3, and that Button does not have the style attribute.

If you need to use the style you must import:

import QtQuick.Controls 1.4

instead of:

import QtQuick.Controls 2.3

If you are using items from Qt Quick Controls and Qt Quick Controls 2 you could separate them using a namespace:

import QtQuick.Controls 2.3 as QQC2
import QtQuick.Controls 1.4 as QQC1

QQC1.Button {
    text: "A button"
    style: ButtonStyle {...}
}

QQC2.another_item_of_Qt_Quick_Controls2{
}



回答2:


You can customize Qt Quick Controls 2 button by modifying its two visual items of background and content item:

https://doc.qt.io/qt-5/qtquickcontrols2-customize.html#customizing-button

import QtQuick 2.12
import QtQuick.Controls 2.12

Button {
    id: control
    text: qsTr("Button")

    contentItem: Text {
        text: control.text
        font: control.font
        opacity: enabled ? 1.0 : 0.3
        color: control.down ? "#17a81a" : "#21be2b"
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        elide: Text.ElideRight
    }

    background: Rectangle {
        implicitWidth: 100
        implicitHeight: 40
        opacity: enabled ? 1 : 0.3
        border.color: control.down ? "#17a81a" : "#21be2b"
        border.width: 1
        radius: 2
    }
}



回答3:


Make sure importing QtQuick.Controls.Styles

import QtQuick.Controls.Styles 1.4
Button {
    text: "A button"
    style: ButtonStyle {...}
}


来源:https://stackoverflow.com/questions/49263604/qml-cannot-assign-to-non-existent-property-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!