我想在QtQuick中使用组件,我有两个qml文件,一个是main.qml和第二个button.qml,iam使用这个示例作为文档,但是当我运行我的代码时,它给我的错误是QQmlApplicationEngine未能加载组件qrc:/bbb/main.qml:13:5: button.qml不是类型。另外,我在main.qml中的导入按钮中看到了一些红色错误。
main.qml
import QtQuick
Window {
id:root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Button { // our Button component
id: button
x: 12; y: 12
text: "Start"
onClicked: {
status.text = "Button clicked!"
}
}
Text { // text changes when button was clicked
id: status
x: 12; y: 76
width: 116; height: 26
text: "waiting ..."
horizontalAlignment: Text.AlignHCenter
}
}
Button.qml
import QtQuick 2.0
Item {
Rectangle {
id: root
// export button properties
property alias text: label.text
signal clicked
width: 116; height: 26
color: "lightsteelblue"
border.color: "slategrey"
Text {
id: label
anchors.centerIn: parent
text: "Start"
}
MouseArea {
anchors.fill: parent
onClicked: {
root.clicked()
}
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/bbb/main.qml"_qs);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
发布于 2022-05-19 22:14:00
您的日志似乎被截断了一些。通常,在这种情况下(对我来说是Qt5.11),这个错误后面是在设计器中可见的invalid property name 'text'
,这是这里真正的问题。
您应该记住,如果信号和属性是在main.qml中最上面的元素上声明的,则信号和属性只能从外部(在您的Button.qml中是如此)可见/可用。似乎您可以简单地删除Item
包装以使其正常工作。
Button.qml:导入QtQuick 2.0
Rectangle {
id: root
// export button properties
property alias text: label.text
signal clicked
width: 116; height: 26
color: "lightsteelblue"
border.color: "slategrey"
Text {
id: label
anchors.centerIn: parent
text: "Start"
}
MouseArea {
anchors.fill: parent
onClicked: {
root.clicked()
}
}
}
https://stackoverflow.com/questions/72314108
复制相似问题