集成c ++和qml

时间:2019-03-15 06:37:46

标签: c++ qt qml

好吧,我正在重新设置整个帖子,因为我想我没有足够的“最小,完整和可验证的示例”,这实际上是我的全部问题,因为我只是在插槽和信号上迷失了。因此,这是第二次尝试,我将省略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(我的类flower(函数)的头)

#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()));

这是我要附加onClicked:命令的带有鼠标区域的导航菜单

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()
            }
           }

当我现在尝试运行时,收到此错误“ W libAHDP.so:QObject :: connect:无法将(null):: qmlClick()连接到(null):: Flower.onClicked()”

我对第一篇文章的道歉很容易引起误解和混淆,我希望对于我的问题更清楚

1 个答案:

答案 0 :(得分:0)

只有QObjects可以具有插槽,因此Flower必须从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()
    }
}

有关更多信息,我建议阅读Best Practices for QML and Qt Quick