qml与C++交互传值的简单demo

qml 与C++的后台交互,参照foruok大神的写法自己研究,改动了一下,有不足 的地方还望路过的大神指出,

我用的是Qt5.7.1,做了个简单的demo,下面是我的代码源码

具体的操作过程如下:

新建选择Application项目 中的Qt Quick Controls 2 Application ,选择下一步,命名为QmlTest后面一直点下一步就行了。

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>
#include <QColor>

class QmlTest : public QObject
{
    Q_OBJECT

public:
    explicit QmlTest(QObject *parent = 0);
    ~QmlTest();

signals:
    void currentDemo(const QString &strDemo);

public slots:
    void send();
};

#endif // QMLTEST_H

qmltest.cpp的源码

#include "qmltest.h"

QmlTest::QmlTest(QObject *parent)
{
}

QmlTest::~QmlTest()
{
}

void QmlTest::send()
{
    emit currentDemo(("demo"));
}

main.qml的源码

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import an.Qt.QmlTest 1.0

ApplicationWindow {
    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;
        }
    }
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值