parent не определен в визуальных дочерних элементах пользовательских QQuickPaintedItem - PullRequest
0 голосов
/ 01 ноября 2019

Полдня я пытаюсь выяснить, почему:

TypeError: Невозможно прочитать свойство 'left' из неопределенного

TypeError: Невозможно прочитать свойство 'right' изundefined

TypeError: Невозможно прочитать свойство 'top' из неопределенного

...

App.qml

ApplicationWindow {
    ViewFactory {
        Component.onCompleted: {
            makeView();
        }
    }
}

Example1.qml

MyView {
    id: root
    Label {
        id: label
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top
        ...
    }
}

В то время как эта версия работает без ошибок:

MyView {
    id: root
    Label {
        id: label
        anchors.left: root.left
        anchors.right: root.right
        anchors.top: root.top
        ...
    }
}

MyView.cpp

MyView::MyView(QQuickItem *parent)
:
    QQuickPaintedItem(parent)
{

}

void MyView::paint(QPainter* painter)
{
     /// @brief draw a rectangle
}

void MyView::setLayout(ViewFactory* layout)
{
    if (_layout == layout) {
        return;
    }

    _layout = layout;
    setParentItem(_layout->parentItem());
    setParent(_layout);
    /// @xxx do I have to emit something by myself when the visual parent is changed?
}

Я создаю экземпляр MyView через QQmlComponent

Q_INVOKABLE void ViewFactory::makeView() {
    // ...
    QQmlComponent component(qmlContext(this)->engine(), QUrl("qrc:/Example1.qml"), QQmlComponent::CompilationMode::PreferSynchronous, this);
    _view = qobject_cast<MyView*>(component.create());

    // ... and set its `parent item` (= visual parent) to parent of current's one(class ViewFactory : public QQuickItem)

    _view->setLayout(this);
    // ...
}

Итак, все сводится к простому вопросу: «Почему parent не определено в контексте ярлыка?»Произошла ли ошибка TypeError, когда у _view нет визуального родителя? Если да, как правильно с этим бороться?

Заранее спасибо.

...