一。qml中用Window方式:
QT += qml quick
qml.qml:
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
width: 200
height: 200
Text {
id: text
anchors.centerIn: parent
text: qsTr("hello world")
}
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
}
main.cpp:
#include <QApplication>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QObject>
#include <QQuickWindow>
#include <QQuickView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QQmlEngine *engine = new QQmlEngine();
QQmlComponent *component = new QQmlComponent(engine);
component->loadUrl(QUrl(QStringLiteral("qrc:/helloworld.qml")));
if(!component->isReady()) {
qWarning("debug %s", qPrintable(component->errorString()));
return -1;
}
QObject::connect(engine, SIGNAL(quit()), &a, SLOT(quit()));
QObject *object = component->create();
QQuickWindow *window = qobject_cast<QQuickWindow*>(object);
window->show();
return a.exec();
}
二。qml中用Rectangle方式:
QT += qml quick
qml.qml:
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
width: 320
height: 240
MouseArea{
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
if(mouse.button === Qt.RightButton) {
Qt.quit()
} else if( mouse.button === Qt.LeftButton) {
color = Qt.rgba((mouse.x % 255) / 255.0, (mouse.y % 255) / 255.0, 0.6, 1.0)
}
}
onDoubleClicked: {
color = "gray"
}
}
}
main.cpp:
//#include "widget.h"
#include <QApplication>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QObject>
#include <QQuickWindow>
#include <QQuickView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QQuickView viewer;
viewer.setResizeMode(QQuickView::SizeRootObjectToView);
viewer.setSource(QUrl(QStringLiteral("qrc:/helloworld.qml")));
QObject::connect(viewer.engine(), SIGNAL(quit()), &a, SLOT(quit()));
viewer.show();
return a.exec();
}
注意区分main文件中的写法。