参考文献:
Integrating QML Code with Existing Qt UI Code
http://qt-project.org/doc/qt-4.8/qml-integration.html
Extending QML Functionalities using C++
http://qt-project.org/doc/qt-4.8/qml-extending.html
Qt 5.0版本C++整合
http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-topic.html
- QWidget添加qml
QDeclarativeView *qmlView = new QDeclarativeView;
qmlView->setSource(QUrl::fromLocalFile("myqml.qml"));
QWidget *widget = myExistingWidget();
QVBoxLayout *layout = new QVBoxLayout(widget);
layout->addWidget(qmlView);
- Qt Quick的C++类注册
test.h
#ifndef TEST_H
#define TEST_H
#include <QObject>
class Test : public QObject
{
Q_OBJECT
Q_PROPERTY (int num READ num WRITE setNum NOTIFY numChanged)
public:
explicit Test(QObject *parent = 0);
const int num() const;
void setNum(const int setValue);
signals:
void numChanged();
public slots:
private:
int m_num;
};
#endif // TEST_H
test.cpp
#include "test.h"
Test::Test(QObject *parent) :
QObject(parent)
{
this->m_num = 0;
}
const int Test::num() const
{
return this->m_num;
}
void Test::setNum(const int setValue)
{
this->m_num = setValue;
emit numChanged(); // 别忘了,不然NOTIFY不会起作用
}
main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
//#include <QQmlEngine>
#include <QtQml>
#include "test.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<Test>("TestQML", 1, 0, "Test");
// 这里注意,“Test”要首字符大写,qml中才能区分属性和标签
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Registry/main.qml"));
viewer.showExpanded();
return app.exec();
}
main.qml
import QtQuick 2.0
import TestQML 1.0
Rectangle {
width: 360
height: 360
Text {
id: text
text: qsTr("Hello World")
anchors.centerIn: parent
}
Item {
width: 5
height: 5
Test {
id: aTest
property int exNum: num
num: 9
onNumChanged:
{
console.debug("aTest.num = " + aTest.num)
}
}
}
Rectangle {
width: 100
height: 100
color: "lightblue"
anchors.horizontalCenter: text.horizontalCenter
anchors.top: text.bottom
anchors.margins: 10
MouseArea {
anchors.fill: parent
onClicked: {
//aTest.num = 1
//aTest.setNum(2)
aTest.num = 7
console.debug("clicked")
console.debug("aTest.num = " + aTest.num)
}
}
}
}