我试图运行以下,但运行它时没有任何反应。我该如何调试这样的问题?
import QtQuick 2.0
import QtQml.Models 2.1
Item{
id: main
width: 1500
height: 1500
GridView {
id: root
width: 1500
height: 1500
cellWidth: 200; cellHeight: 200
visible: true
model: DelegateModel {
model: ListModel {
ListElement {
color: "blue"
}
ListElement {
color: "white"
}
ListElement {
color: "red"
}
ListElement {
color: "green"
}
ListElement {
color: "orange"
}
ListElement {
color: "yellow"
}
ListElement {
color: "grey"
}
}
delegate: MouseArea {
objectName: "mousearea"
implicitHeight: parent.height
implicitWidth: parent.width
Rectangle {
anchors.fill: parent
color: model.color
}
drag{
target: parent
}
}
}
}
}
我打算从这段代码中得到以下内容:在GridView
中创建几个矩形并向它们添加一个MouseArea
,然后尝试拖动它们。我不确定我的模型结构是否正确。
编辑:添加main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
QQmlApplicationEngine期望将一个Window作为根元素,如docs所示:
... 与QQuickView不同,QQmlApplicationEngine不会自动创建根窗口。如果您使用Qt Quick中的可视项目,则需要将它们放在窗口内。 ...
所以解决方案很简单,按窗口更改项目:
main.qml
import QtQuick 2.0
import QtQuick.Window 2.11
import QtQml.Models 2.1
Window{
visible: true
id: main
width: 1500
height: 1500
GridView {
id: root
width: 1500
height: 1500
cellWidth: 200; cellHeight: 200
visible: true
model: DelegateModel {
model: ListModel {
ListElement {
color: "blue"
}
ListElement {
color: "white"
}
ListElement {
color: "red"
}
ListElement {
color: "green"
}
ListElement {
color: "orange"
}
ListElement {
color: "yellow"
}
ListElement {
color: "grey"
}
}
delegate: MouseArea {
objectName: "mousearea"
implicitHeight: parent.height
implicitWidth: parent.width
Rectangle {
anchors.fill: parent
color: model.color
}
drag{
target: parent
}
}
}
}
}