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; } }}
新闻热点
疑难解答
图片精选