我的目标是创建一个自定义组件(让我们称之为ComponentLoader),它可以通过委托实例化另一个组件(让我们称之为DelegateComponent)。
问题是DelegateComponent实例在创建后不会显示(白色屏幕)。注意:存在tst_component is loaded消息,这意味着实际创建了DelegateComponent实例。
下面是一个很小的例子:
main.qml
ApplicationWindow {
id: mainWindow
width: 640
height: 480
visible: true
Component {
id: tst_component
Rectangle {
anchors.fill: parent
Component.onCompleted: {
console.debug("tst_component is loaded");
}
Label {
text: "hello world"
anchors.centerIn: parent
}
}
}
// doesn't work
ComponentLoader {
anchors.fill: parent
delegate: tst_component
}
// works
// Loader {
// anchors.fill: parent
// sourceComponent: tst_component
// }
}组件加载器.h+ componentloader.cpp
#pragma once
#include <QQuickItem>
class ComponentLoader : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(QQmlComponent* delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
public:
QQmlComponent* delegate() const;
void setDelegate(QQmlComponent*);
signals:
void delegateChanged();
private:
void generate();
protected:
void componentComplete() override;
private:
QQmlComponent* mDelegate = nullptr;
};
// componentloader.cpp
#include "componentloader.h"
#include <QtWidgets/QtWidgets>
#include <QtQmlModels/QtQmlModels>
#include <QQuickWindow>
QQmlComponent* ComponentLoader::delegate() const
{
return mDelegate;
}
void ComponentLoader::setDelegate(QQmlComponent* delegate)
{
if (delegate != mDelegate)
{
mDelegate = delegate;
emit delegateChanged();
}
}
void ComponentLoader::componentComplete()
{
QQuickItem::componentComplete();
generate();
}
void ComponentLoader::generate()
{
QQmlEngine* engine = qmlEngine(this);
QQmlContext* root_ctx = engine->rootContext();
QQmlContext* ctx = new QQmlContext(root_ctx);
QObject* item = mDelegate->create(ctx);
QQuickItem* quickItem = qobject_cast<QQuickItem*>(item);
QQuickItem* quickParent = qobject_cast<QQuickItem*>(parent());
quickItem->setParent(quickParent);
quickItem->setParentItem(quickParent);
}发布于 2022-05-20 13:45:29
quickParent指针采用的是QObject父()值,而不是QQuickItem parentItem()值。
当我尝试使用您的代码时,简单地将它更改为这样对我是有效的:
QQuickItem* quickParent = qobject_cast<QQuickItem*>(parentItem());我也不认为您需要调用setParent()。只有setParentItem()。
https://stackoverflow.com/questions/72318119
复制相似问题