How to change the Button's background color? My qt version is 6.4.3
-
I want to change the background color of the button, but the default style can not be overridden. How can I solve this problem
import QtQuick import QtQuick.Controls Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Button { id: button text: qsTr("Button text") background: Rectangle { color: parent.down ? "green" : (parent.hovered ? "blue" : "red") } } }
When I move the mouse over the button, the default styles override my custom styles
-
I follow the official document to operate, is my custom button method wrong?
-
@xgj1 Not all Qt Quick Controls Styles can be customized : https://doc.qt.io/qt-6/qtquickcontrols-customize.html#customization-reference
My guess is that you are under Windows.
The recommended way to use Qt Quick Controls now is not to use dynamic styling but to import a specific style.So no
import QtQuick.Controls
, instead useimport QtQuick.Controls.Basic
(or Fusion, Material, Universal) -
@xgj1 what @GrecKo said is probably what is happening to you. You might try adding something like this to your main.cpp:
#include <QSysInfo> const QString platform = QSysInfo::productType(); QString l_styleName; l_styleName = (platform == "android") ? "Material" : (platform == "windows") ? "Universal" : "Fusion"; QQuickStyle::setStyle(l_styleName);
-
@GrecKo You are right, the cause is the style he is using has something else on top of the
background
. So one should use aBasic
,... style.
Good to know.
He could select the style also at runtime,
https://doc.qt.io/qt-6/qtquickcontrols-styles.html#using-styles-in-qt-quick-controls
But as you said, compile-time style selection is better for these custom components.
In any case, I do not thinkparent
inside theRectangle
is good.