qml_初步认识
qml_初步认识
qml语法认识
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
view.show();
return app.exec();
}
//qrc:/main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick 2.3
Image {
id: hz1
source: "/image/hz1.jpg"
}
信号和槽
// application_data.h
#ifndef APPLICATION_DATA_H
#define APPLICATION_DATA_H
#include <QObject>
#include <QDateTime>
#include <QTimer>
class ApplicationData : public QObject
{
Q_OBJECT
public:
ApplicationData() {
// 定时器
QTimer *pTimer = new QTimer(this);
pTimer->setInterval(1000);
connect(pTimer, &QTimer::timeout, this, &ApplicationData::onTimeout);
pTimer->start();
}
Q_INVOKABLE QDateTime getCurrentDateTime() const {
return m_dateTime;
}
signals:
void dataChanged();
private slots:
void onTimeout() {
m_dateTime = QDateTime::currentDateTime();
emit dataChanged(); // 超时后发射信号
}
private:
QDateTime m_dateTime;
};
#endif // APPLICATION_DATA_H
// main.qml
import QtQuick 2.3
Rectangle {
width: 200; height: 100
Text {
id: timer
anchors.centerIn: parent
text: "Timer"
}
Connections { // 连接信号
target: applicationData
onDataChanged: {
timer.text = applicationData.getCurrentDateTime()
console.log("The application data changed!")
}
}
}
加载qml对象的方法
// 使用 QQmlComponent
QQmlEngine engine;
QQmlComponent component(&engine, QUrl("qrc:/main.qml"));
QObject *object = component.create();
//...
delete object;
// 使用 QQuickView
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
view.show();
QObject *object = view.rootObject();
定位qml的相关值
// main.qml
import QtQuick 2.3
Item {
width: 100; height: 100
Rectangle {
anchors.fill: parent
objectName: "rect"
}
}
QObject *rect = object->findChild<QObject*>("rect");
if (rect)
rect->setProperty("color", "red");
调用qml的方法
// main.qml
import QtQuick 2.3
Item {
function myQmlFunction(msg) {
console.log("Got message:", msg)
return "Hello, Qter!"
}
}
// main.cpp
QQmlEngine engine;
QQmlComponent component(&engine, QUrl("qrc:/main.qml"));
QObject *object = component.create();
QVariant returnedValue; // 返回值
QVariant msg = "Hello, QML!"; // 方法参数
// 调用 QML 方法
QMetaObject::invokeMethod(object, "qmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));
qDebug() << "QML function returned:" << returnedValue.toString();
delete object;