这里总结了三种qml主界面启动的方式。
- qml主界面是Window或者是ApplicationWindow
在main.cpp中可以使用
QQmlApplicationEngine engine
engine.load(QUrl(QStringLiteral(“qrc:/main.qml”)));
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();
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
Window
{
width:400
height:500
visible: true
MessageDialog {
id:id_mesDialog
title: "这是一个提示框"
icon: StandardIcon.Question
text: "是否继续?"
standardButtons: StandardButton.Yes |StandardButton.No
Component.onCompleted: visible = false
onYes: console.log("YES")
onNo: console.log("NO")
onRejected: console.log("Close")
}
Button{
text: qsTr("点击")
anchors.centerIn:parent
onClicked: id_mesDialog.open()
}
}
- qml中的主界面是Rectangle
在main.cpp中可以使用
QQuickView viewer
viewer.setSource(“main.qml”)
viewer.show();
main.cpp
#include <QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQuickView viewer;
viewer.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
viewer.show();
return app.exec();
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 1.2
Rectangle
{
width:400
height:500
visible: true
Rectangle {
anchors.margins: 8;
anchors.top: parent.top;
anchors.left: parent.left;
anchors.right: parent.right;
anchors.bottom: parent.bottom;
color: "lightgray";
Component {
id: tabContent;
Rectangle {
implicitWidth: 100;
implicitHeight: 100;
anchors.fill: parent;
color: Qt.rgba(Math.random(), Math.random(), Math.random());
}
}
Button {
id: addTab;
x: 8;
y: 8;
width: 60;
height: 25;
text: "AddTab";
onClicked: {
tabView.addTab("tab-" + tabView.count, tabContent);
}
}
TabView {
id: tabView;
anchors.top: addTab.bottom;
anchors.margins: 8;
anchors.left: parent.left;
anchors.right: parent.right;
anchors.bottom: parent.bottom;
}
}
}
- 在开发机中可以 qmlscene.exe main.qml