gpt4 book ai didi

c++ - 如何在 QML 和 Qt 中访问 QObject* 的 QList?

转载 作者:行者123 更新时间:2023-11-28 06:27:58 24 4
gpt4 key购买 nike

我需要一个类对象数组,它应该可以在 Qt 和 QML 中访问。

考虑https://stackoverflow.com/a/15830797/462608以下是我尝试过的。

现在我需要知道如何通过QtQML读写ClassA的函数。

见.h文件中构造函数中的打印语句。这会产生段错误。

class.h

#ifndef CLASSA
#define CLASSA

#include <QQuickItem>

class ClassA : public QObject
{
private:
Q_OBJECT

Q_PROPERTY(int one READ one WRITE setOne NOTIFY oneChanged)
int m_one;

public:
ClassA () {}
int one() const { return m_one; }

public slots:
void setOne(int arg)
{
if (m_one == arg)
return;

m_one = arg;
emit oneChanged(arg);
}

signals:
void oneChanged(int arg);
};

class ClassB : public QObject
{
private:
Q_OBJECT

Q_PROPERTY(QList <QObject*> objClassAList READ objClassAList WRITE setObjClassAList NOTIFY objClassAListChanged)
QList <QObject*> m_objClassAList;

public:
ClassB ()
{
QList <QObject*> localObjList;
for (int i = 0; i < 5; i++)
{
ClassA localObj;
localObj.setOne (100);
localObjList.push_back (&localObj);
}

setObjClassAList (localObjList);
qDebug () << "QQQQQQQQQQQQQQ: " << objClassAList ()[0]->property ("one");
}

QList <QObject*> objClassAList () const { return m_objClassAList; }

public slots:
void setObjClassAList (QList <QObject*> arg)
{
if (m_objClassAList == arg)
return;

m_objClassAList = arg;
emit objClassAListChanged(arg);
}

signals:
void objClassAListChanged (QList <QObject*> arg);
};

#endif // CLASSA

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "class.h"

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);

const char* what = "WHAT";

qmlRegisterType <ClassA> (what, 1, 0, "A");
qmlRegisterType <ClassB> (what, 1, 0, "B");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

return app.exec();
}

ma​​in.qml

import QtQuick 2.4
import QtQuick.Window 2.2
import WHAT 1.0

Window {
visible: true

B
{
onObjClassAListChanged:
{

}
}
}

最佳答案

问题是您正在尝试访问分配在堆栈上的删除指针。相反,在堆上分配 ClassA,它应该可以解决您的问题。

ClassB ()
{
QList <QObject*> localObjList;
for (int i = 0; i < 5; i++)
{
ClassA localObj; //This object is delete after it goes out of scope
localObj.setOne (100);
localObjList.push_back (&localObj); //After this line &localObj is a dangling pointer to delete memory
}

setObjClassAList (localObjList);
qDebug () << "QQQQQQQQQQQQQQ: " << objClassAList ()[0]->property ("one");
}

例如,我建议修改为:

ClassB ()
{
QList <QObject*> localObjList;
for (int i = 0; i < 5; i++)
{
ClassA localObj = new ClassA();
localObj->setOne (100);
localObjList.push_back(localObj);
}

setObjClassAList (localObjList);

//This should work now.
qDebug () << "QQQQQQQQQQQQQQ: " << objClassAList ()[0]->property ("one");
}

这应该可以解决您的段错误。其他一切看起来都很好。

关于c++ - 如何在 QML 和 Qt 中访问 QObject* 的 QList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188639/

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