Integrating c++ and qml

Integrating c++ and qml

本文关键字:qml and c++ Integrating      更新时间:2023-10-16

好吧,我要重置整个帖子,因为我想我没有足够的"最小,完整和可验证的示例",这实际上是我的整个问题,因为我只是我只是因此在插槽和信号上丢失了..所以这是第二尝试,我将遗漏flower.cpp,但知道它在那里具有功能

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QtQuick>
#include <QNetworkAccessManager>
#include <iostream>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QObject>
#include "flower.h"

void Flower::onClicked(){
//code i've been trying to test all day
}

flower.h(我的类花的标题(功能))

#ifndef FLOWER_H
#define FLOWER_H
#include <QObject>
class Flower
{
private slots:
void onClicked();
};
#endif // FLOWER_H

main.cpp(这是我的应用QML启动的地方,我正在尝试设置信号和插槽的连接)

QQuickView home;
home.setSource(QUrl::fromLocalFile("main.qml"));
home.show();
QObject *homePa = home.rootObject();
QObject *buttF = homePa->findChild<QObject*>("buttFObject");
QObject::connect(buttF, SIGNAL(qmlClick()), buttF,
                 SLOT(Flower.onClicked()));

这是我想登录的Mousearea的NavMenu:命令

Rectangle {
    signal qmlClick();
    id: navMenu
    color: "#00000000"
    radius: 0
    anchors.fill: parent
    z: 3
    visible: false
    border.width: 0
    transformOrigin: Item.Center
               MouseArea {
                id: buttFArea
                objectName: buttFObject
                anchors.fill: parent
                onClicked: navMenu.qmlClick()
            }
           }

当我现在尝试运行时,我会收到此错误。>

对我的第一篇文章非常误导和混杂表示歉意,我希望我的问题更清楚

只有qobjects才能具有插槽,因此花必须从qobject继承。另一方面,您正在使用一种总是带来试图从C 获得QML元素的问题,而必须使用setContextProperty()将C 元素导出到QML:

flower.h

#ifndef FLOWER_H
#define FLOWER_H
#include <QObject>
class Flower : public QObject
{
    Q_OBJECT
public:
    explicit Flower(QObject *parent = nullptr);
    Q_SLOT void onClicked();
};
#endif // FLOWER_H

flower.cpp

#include "flower.h"
#include <QDebug>
Flower::Flower(QObject *parent) : QObject(parent)
{}
void Flower::onClicked()
{
    qDebug()<< __PRETTY_FUNCTION__;
}

main.cpp

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include "flower.h"
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    Flower flower;
    QQuickView view;
    view.rootContext()->setContextProperty("flower", &flower);
    view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    view.show();
    return app.exec();
}

main.qml

import QtQuick 2.9
Rectangle {
    color: "#00000000"
    anchors.fill: parent
    transformOrigin: Item.Center
    MouseArea {
        id: buttFArea
        anchors.fill: parent
        onClicked: flower.onClicked()
    }
}

有关更多信息,我建议阅读QML和QT快速

的最佳实践