QML-C++混合编程

qml c++ 混合编程

简单的开始例子

编写c++ class

// backend.h
#ifndef BACKEND_H
#define BACKEND_H

#include <QObject>

class BackEnd : public QObject
{
    Q_OBJECT
    //使用Q_PROPERTY 为类添加属性,可供qml直接使用
    Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged)
public:
    explicit BackEnd(QObject *parent = nullptr);

    QString userName();
    void setUserName(const QString& userName);

signals:
    void userNameChanged();//可以被QML使用 onUserNameChanged

public slots:

private:
    QString _userName;
};

#endif // BACKEND_H

//bakcend.cpp
  #include "backend.h"

  BackEnd::BackEnd(QObject *parent) :
      QObject(parent)
  {
  }

  QString BackEnd::userName()
  {
      return m_userName;
  }

  void BackEnd::setUserName(const QString &userName)
  {
      if (userName == m_userName)
          return;

      m_userName = userName;
      emit userNameChanged();
  }

注册class

#include <QGuiApplication>
#include <QQmlApplicationEngine>

#include "backend.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

	//注册backend(url, versionMajor, versionMinor, qmlName)
    qmlRegisterType<BackEnd>("io.qt.examples.backend", 1, 0, "BackEnd");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

使用demo

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4

import io.qt.examples.backend 1.0
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    BackEnd {
        id: backend;
        userName: "test"
    }

    TextField {
        text: backend.userName
        placeholderText: qsTr("User Name")
        anchors.centerIn: parent

        onTextChanged:
        {
            backend.userName = text
            console.log(backend.userName)
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值