我对通过c++ QQuickItem访问qml父对象的属性很感兴趣。我有一个自定义的QQuick项,名为VisibleTag the extends。任何包含此对象标签的qml项,我都希望根据我在代码中设置的其他因素将其设置为可见或不可见,出于这个问题的目的,我暂时删除了这些因素。然而,我遇到了一个问题,我的父指针在构造时为空。
//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() );
}相反,我希望让父指针指向qml的可视父项。在这个例子中,我希望parent指向Rectangle opPic。
我是不是误解了QQuickItem构造函数的工作方式?是否可以访问qml可视父级?
发布于 2020-02-11 04:45:58
通过QML构造QQuickItem不是:
T* o = new T(parent);但
T* o = new T;
T->setParentItem(parent);所以您不能在构造函数中获取父对象,但必须在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());
}https://stackoverflow.com/questions/60157548
复制相似问题