[英]QQuickItem parent item null in constructor
I am interested in accessing attributes of a qml parent through a c++ QQuickItem.我对通过 c++ QQuickItem 访问 qml 父级的属性感兴趣。 I have a custom QQuick item called VisibleTag the extends QQuickItem.
我有一个名为 VisibleTag 的自定义 QQuick 项目,它扩展了 QQuickItem。 Any qml item containing this object Tag, I would like set as visible or invisible based off other factors I set in my code that I temporarily removed for the purposes of this question.
任何包含此对象标签的 qml 项目,我都希望根据我在代码中设置的其他因素设置为可见或不可见,为了这个问题我暂时删除了这些因素。 However, I am having an issue where my parent pointer is null on construction.
但是,我遇到了一个问题,即我的父指针在构造时为空。
//main.cpp
#include <QtQuick/QQuickView>
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<VisibleTag>("VisibleTag", 1, 0, "VisibleTag");
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///app.qml"));
view.show();
return app.exec();
}
//app.aml
Rectangle{
id: opPic
height: 100
width: 100
color: "red"
VisibleTag{}
}
//header
class VisibleTag : public QQuickItem
{
Q_OBJECT
public:
VisibleTag( QQuickItem* parent = nullptr );
private:
bool isVisible() { return false; } //this is a dummy function for testing my issue
}
//cpp
VisibleTag::VisibleTag( QQuickItem* parent )
: QQuickItem( parent )
{
//qDebug() << parent->objectName(); //This line will break because parent is null
parent->setVisible( isVisible() );
}
I would expect instead to have the parent pointer to point to the qml's visual parent item.我希望让父指针指向 qml 的可视父项。 In the example, I would expect parent to point to Rectangle opPic.
在这个例子中,我希望 parent 指向 Rectangle opPic。
Am i misunderstanding how the QQuickItem constructor works?我误解了 QQuickItem 构造函数的工作原理吗? Is is possible to access a qml visual parent?
是否可以访问 qml 视觉父级?
The construction of an QQuickItem by QML is not: QML 对 QQuickItem 的构建不是:
T* o = new T(parent);
but但
T* o = new T;
T->setParentItem(parent);
So you can't get the parent in the constructor but you have to do it in the componentComplete()
method (similar to Component.onCompleted
in QML):因此,您无法在构造函数中获取父级,而必须在
componentComplete()
方法中获取(类似于 QML 中的Component.onCompleted
):
#ifndef VISIBLETAG_H
#define VISIBLETAG_H
#include <QQuickItem>
class VisibleTag : public QQuickItem
{
Q_OBJECT
public:
VisibleTag(QQuickItem *parent=nullptr);
protected:
void componentComplete();
private:
bool dummy() { return false; }
};
#endif // VISIBLETAG_H
#include "visibletag.h"
VisibleTag::VisibleTag(QQuickItem *parent):QQuickItem(parent)
{
}
void VisibleTag::componentComplete()
{
if(parentItem())
parentItem()->setVisible(dummy());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.