Qml中调用C++类的三种方式详解(三)

C++创建/获取Qml对象

第一步:新建一个 QmlWindows.qml文件:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window{
    width: 200
    height: 200
    color: "red"
}

定义了一个200*200 的红色矩形框,还没有开始使用。

第二步:在main.cpp文件中使用 c++的形式创建 

首先在头文件中加入:

#include <QQmlComponent>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "qmlcpp.h"
#include <QJSValue>
#include <QQmlEngine>
#include <QQmlComponent>

int main(int argc, char *argv[])
{
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);

    }, Qt::QueuedConnection);
    engine.load(url);

    QQmlComponent qmlComponent(&engine);
    qmlComponent.loadUrl(QUrl(QStringLiteral("qrc:/QmlWindow.qml")));
    QObject* qmlWindows = qmlComponent.create();
    qmlWindows->setParent(engine.rootObjects()[0]);
    engine.rootContext()->setContextProperty("qmlWindows",qmlWindows);

    return app.exec();
}

主要代码是:

 QQmlComponent qmlComponent(&engine);  
qmlComponent.loadUrl(QUrl(QStringLiteral("qrc:/QmlWindow.qml")));    
QObject* qmlWindows = qmlComponent.create();    
qmlWindows->setParent(engine.rootObjects()[0]);    
engine.rootContext()->setContextProperty("qmlWindows",qmlWindows);

其中   engine.rootObjects()[0] 指的是主窗体。

第三步,在其他的qml文件中就可以直接进行调用

import QtQuick 2.12
import QtQuick.Controls 2.12


Item {


    Button{
        id:btn
        height: 48
        width: 120
        text: "1"
        anchors.centerIn: parent

        onClicked: {
            qmlWindows.color="green";
            qmlWindows.width=200;
            qmlWindows.visible = true;
        }
    }
    Button{
        id:btn1
        height: 48
        width: 120
        anchors.top: btn.bottom
        anchors.topMargin: 12
        anchors.horizontalCenter: btn.horizontalCenter
        onClicked: {

            qmlWindows.width=400;
            qmlWindows.color="yellow"

        }
    }
}

点击第一个按钮,使得 qmlWindows.qml这个 红色矩形 变为绿色,并可见

点击第一个按钮,使得 qmlWindows.qml这个 矩形 变为黄色,并使得宽度为400。


 

在 Qt ,可以通过在 QML 使用 `Qt.createQmlObject()` 或者 `Qt.createComponent()` 创建一个 C++ 对象,然后在 QML 调用该对象的方法或者访问其属性。 具体步骤如下: 1. 在 C++ 定义一个 QObject 的子,并在其声明 Q_INVOKABLE 的方法或者 Q_PROPERTY 的属性。 ```cpp // MyObject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <QObject> class MyObject : public QObject { Q_OBJECT public: explicit MyObject(QObject *parent = nullptr); Q_INVOKABLE void myMethod(QString str); Q_PROPERTY(QString myProperty READ myProperty WRITE setMyProperty NOTIFY myPropertyChanged) void setMyProperty(const QString &str); QString myProperty() const; signals: void mySignal(); void myPropertyChanged(); }; #endif // MYOBJECT_H ``` ```cpp // MyObject.cpp #include "MyObject.h" MyObject::MyObject(QObject *parent) : QObject(parent) { } void MyObject::myMethod(QString str) { qDebug() << "myMethod called with arg" << str; } void MyObject::setMyProperty(const QString &str) { if (m_property != str) { m_property = str; emit myPropertyChanged(); } } QString MyObject::myProperty() const { return m_property; } ``` 2. 在 main.cpp 将该对象注册到 QML ,以便在 QML 访问。 ```cpp // main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include "MyObject.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<MyObject>("com.mycompany.myobject", 1, 0, "MyObject"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); } ``` 3. 在 QML 使用 `Qt.createComponent()` 或者 `Qt.createQmlObject()` 创建该对象,并调用其方法或者访问其属性。 ```qml // main.qml import QtQuick 2.0 import com.mycompany.myobject 1.0 Rectangle { width: 400 height: 400 MyObject { id: myObject myProperty: "Hello, World!" Component.onCompleted: { myObject.myMethod("Hello, World!"); console.log(myObject.myProperty); } } } ``` 在上述代码,我们使用 `MyObject` 创建了一个名为 `myObject` 的对象,并调用了它的 `myMethod` 方法和 `myProperty` 属性。 需要注意的是,使用 `Qt.createComponent()` 或者 `Qt.createQmlObject()` 创建对象时,必须指定该对象的父对象,否则该对象将无法正常工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值