最新QT5.9出来了,多了很多新特性,感觉不错。本文是QT5.9 Qt Creator 4.3.1环境。
第一步:点击NEW Project新建工程
第二步:选择QT Quick Application
第三步:项目名称和项目存放路径,都自己取,在这儿取名叫QML_test_1,选择下一步
第四步:选择默认qmake
第五步:选择项目支持最小的QT版本,可以自己着情选择,我喜欢不选择with ui.qml file,这个选择会自动加上一个通过拖拽控件去设计界面,喜欢这样的可以自己看看。
第六步:选择kits,我是全选
第七步:一路下一步就好,新建完成。
main.cpp中代码
#include<QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
QML通过QQmlApplicationEngine引擎加载。
main.qml自动生成的代码如下:
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true //设置窗口是否显示,true的时候显示本窗口,false不显示
width: 640 //宽
height: 480 //高
title: qsTr("Hello World") //窗口标题
MouseArea { //鼠标点击事件
anchors.fill: parent //鼠标点击区域整个窗口
onClicked: {//点击事件
console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"'))
}
}
TextEdit {//文本编辑控件
id: textEdit
text: qsTr("Enter some text...")
verticalAlignment: Text.AlignVCenter //文本显示的位置
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
anchors.topMargin: 20
Rectangle {
anchors.fill: parent
anchors.margins: -10
color: "transparent"
border.width: 1
}
}
}
代码中建了个window窗口。
点击运行:
点击窗口会在输出哪儿打印