15

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
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
vincedjango
  • 1,022
  • 1
  • 13
  • 24

3 Answers3

24

There are 2 types of Buttons in QML:

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{
}
Soheil Armin
  • 2,725
  • 1
  • 6
  • 18
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thank you! It is a great and clear answer. I don't understand why some people downvoted this question. The documentation wasn't clear about it. – vincedjango Mar 13 '18 at 19:15
3

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
    }
}
Megidd
  • 7,089
  • 6
  • 65
  • 142
0

Make sure importing QtQuick.Controls.Styles

import QtQuick.Controls.Styles 1.4
Button {
    text: "A button"
    style: ButtonStyle {...}
}
Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47