使用QT,新建Qml(qt quick)工程。
main.qml如下:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
Window {
visible: true
width: 300
height: 300
title: qsTr("Hello World")
ListModel { // Model
id : listModel
ListElement { name : "Blue" }
ListElement { name : "Red" }
ListElement { name : "Green" }
}
ComboBox { // View
id : comboBox
anchors.centerIn: parent
model: listModel
onCurrentTextChanged: {
dispText()
}
}
function dispText() { // Controller
console.log(comboBox.currentText)
}
}
main.cpp如下:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[]) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
运行结果如下:
说明:Qml自带的MVC模式,由ListModel做为model,控件ComBoBox做为View(也可以使用其它可视化控件),js做为controller。model也就是数据,这里将数据、显示、控制分离开,实现解耦。
|