有群友抛出类似以下代码和运行效果截图:
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Button
{
anchors.centerIn: parent
width: 100
height: 40
background: Rectangle {
color: "red"
}
}
}
并提问(群友原话):
- 这个为什么有蓝框
- qml里边
- 有人知道吗
- 咋去掉
粗略一看,我寻思这莫不是消遣我?就这几行 QML 怎么可能出问题。但为了堵住群友的嘴,于是也建了个新工程加入以上代码,运行良好,截图发给群友以证明是群友人的问题。运行效果如图:
谁知群友看了后仍然是叫苦不迭,让人有点疑惑。仔细查看代码后,发现群友代码中对 QtQuick 控件的包含为:import QtQuick.Controls,于是明白群友是 Qt6 的环境(Qt5 import 组件需要加入版本号),切换 Qt6 环境后,复现了群友的问题,并发现控制台运行时报错:
qrc:/xx/Main.qml:16:21: QML QQuickRectangle: The current style does not support customization of this control (property: “background” item: QQuickRectangle(0x14f497fe250, parent=0x0, geometry=0,0 0x0)). Please customize a non-native style (such as Basic, Fusion, Material, etc). For more information, see: https://doc.qt.io/qt-6/qtquickcontrols2-customize.html#customization-reference
由于没怎么用 Qt6 的 QtQuick,所有此错误还是第一次遇到,根据提示复制错误中最后的链接,看到Qt官方文档中如下内容:
给出的样例中,import 组件使用的是:
import QtQuick.Controls.Basic
与Qt5不同的是,对 QtQuick.Controls 的引入后面加了 .Basic,查看文档上下文,大概意思就是可以自定义 style,Basic 可看做 Qt5 QtQuick.Controls 的默认 style,不加 .Basic 的情况下,以WIndows操作系统为例,会认为你默认使用了.Windows,而这种 style 不支持覆盖 background 属性,如图加入 .Windows 后 IDE 给出警告:
修改为 import QtQuick.Controls.Basic 就可正常运行。
看来 Qt6 对 QtQuick 的大改,所言非虚。群友终于有用了一回。