qml c++ 混合编程
简单的开始例子
编写c++ class
#ifndef BACKEND_H
#define BACKEND_H
#include <QObject>
class BackEnd : public QObject
{
Q_OBJECT
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();
public slots:
private:
QString _userName;
};
#endif
#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);
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)
}
}
}