gpt4 book ai didi

c++ - 整合c++和qml

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:56 26 4
gpt4 key购买 nike

好吧,我正在重置整个帖子,因为我想我没有足够的“最小、完整和可验证的示例”,这确实是我的全部问题,因为我对插槽和信号太迷茫了……所以这是第二次尝试,我将省略 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()));

这是带有鼠标区域的导航菜单,我想附加 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()”

为我的第一篇文章误导和混淆而道歉我希望这更清楚我的问题是什么

最佳答案

只有 QObject 可以有槽,所以 Flower 必须继承自 QObject。另一方面,您使用的方法总是会带来问题,即尝试从 C++ 获取 QML 元素,而您必须使用 setContextProperty() 将 C++ 元素导出到 QML:

花.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

花.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();
}

ma​​in.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

关于c++ - 整合c++和qml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55176915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com