qml 與C++的后臺交互,參照foruok大神的寫法自己研究,改動了一下,有不足 的地方還望路過的大神指出,
我用的是Qt5.7.1,做了個簡單的demo,下面是我的代碼源碼
具體的操作過程如下:
新建選擇application項目 中的Qt Quick Controls 2 Application ,選擇下一步,命名為QmlTest后面一直點下一步就行了。
選擇項目右鍵選擇添加新文件,C++ C++ Class 下一步,命名為QmlTest,baseClass選擇QObject點擊下一步就OK了。
main.cpp的源碼
#include <QGuiApplication>#include <QQmlApplicationEngine>#include <QtQml>#include "qmltest.h"int main(int argc, char *argv[]){ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); qmlRegisterType<QmlTest>("an.Qt.QmlTest",1,0,"QmlTest"); QQmlApplicationEngine engine; engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec();}注意上面的 qmlRegisterType<QmlTest>("an.Qt.QmlTest",1,0,"QmlTest");的位置不能放錯否則會沒有作用。
qmltest.h的源碼
#ifndef QMLTEST_H#define QMLTEST_H#include <QObject>class QmlTest : public QObject{ Q_OBJECTpublic: explicit QmlTest(QObject *parent = 0); ~QmlTest();signals: void currentDemo(const QString &strDemo);public slots: void send();};#endif // QMLTEST_Hqmltest.cpp的源碼
#include "qmltest.h"QmlTest::QmlTest(QObject *parent){}QmlTest::~QmlTest(){}void QmlTest::send(){ emit currentDemo(("demo"));}main.qml的源碼
import QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.0import an.Qt.QmlTest 1.0ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Text { id: demoLabel; anchors.left: parent.left; anchors.leftMargin: 4; anchors.top: parent.top; anchors.topMargin: 4; font.pixelSize: 26; } QmlTest { id: demoMaker; } Button{ id:send; text: "send"; anchors.left: parent.left; anchors.leftMargin: 4; anchors.bottom: parent.bottom; anchors.bottomMargin: 4; onClicked: { demoMaker.send(); } } Connections { target: demoMaker; onCurrentDemo:{ demoLabel.text = strDemo; } }}
新聞熱點
疑難解答
圖片精選