QML与Qt程序
Qt Declarative UI运行环境
QML文档通过QML运行环境载入并运行. 包含Declarative UI引擎和内置的QML元素, 插件模块, 还提供了访问第三方的QML元素与模块.
QML与Qt
单纯使用QML可以不了解Qt, 但是如果想设计一个数据逻辑和UI分开的结构, 则需要用到Qt;
QML可直接访问的Qt类:
QAction, signal and slot(can be used as function in JavaScript),
QWidget--QDeclarativeView(Qt5使用QQuickView代替, 属于QWindow, 不用QWidget),
Qt Model--QAbstractItemModel
QML Tools
查看和调试QML的工具: qmlviewer
command: qmlviewer.exe filename.qml
将C++类注册成为QML类型
1
2
|
#include <QtQml>
qmlRegisterType<MySliderItem>(
"com.mycompany.qmlcomponents"
, 1, 0,
"Slider"
);
|
使用:
1
2
3
4
|
import com.mycompany.qmlcomponents 1.0
Slider {
// ...
}
|
以C++类创建QML属性
1)inherited from QObject
2)declarate the Marco: Q_OBJECT(meta system), Q_PROPERTY(QML property)
Declarative UI
QDeclarativeView加载QML文件
QDeclarativeView是一个QWidget(QAbstractScrollArea), 可以加载QML文件;
1
2
3
|
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile(
"app.qml"
));
view.show();
|
PRO工程文件
1
|
QT += gui declarative
|
QDeclarativeEngine
可以直接加载QML, 创建QObject来进行操作;
每个程序至少需要一个Engine, 可以配置全局设置应用到所有的QML组件中;
QDeclarativeEngine: 提供了一个实例化QML Component的环境;
QDeclarativeComponent: 封装QML Component的一个类;
QDeclarativeContext: 定义了一个通过QML engine工作的context, 可以将数据暴露给QML component;
1
2
3
4
|
QDeclarativeEngine engine;
QDeclarativeContext *windowContext =
new
QDeclarativeContext(engine.rootContext());
QDeclarativeComponent component(&engine,
"application.qml"
);
QObject *window = component.create(windowContext);
|
Note 对于shadow build, qml文件需要放到build路径中;
加上数据
>背景颜色
1
2
3
|
QDeclarativeContext *context = view.rootContext();
context->setContextProperty(
"backgroundColor"
,QColor(Qt::yellow));
view.setSource(QUrl::fromLocalFile(
"main.qml"
));
|
当不需要QDeclarativeView显示组件时, 可以使用QDeclarativeEngine::rootContext()代替