升级到Qt 5.15后,ListView委托中的Parent为null

问题描述

如果一个ListView具有最简单的委托,则尝试设置其委托"21:35:31.911 warning T#16084047 unknown - qrc:/main.qml:15: TypeError: Cannot read property 'left' of null"属性并滚动列表(会使委托被销毁/创建)会产生很多警告anchors。在Qt 5.12或5.9中不是这种情况。

文件main.qml

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    ListView {
        anchors.fill: parent
        model: cppModel

        delegate: Rectangle {
            anchors.left: parent.left
            anchors.right: parent.right
            height: 50

            Text { text: model.itemName }
        }
    }
}

文件main.cpp

#include <QAbstractListModel>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtGlobal>
#include <QQmlContext>

#include <iostream>

void myMessageHandler(QtMsgType type,const QMessageLogContext &context,const QString &msg) {
    QString logLine = qFormatLogMessage(type,context,msg);
    std::cout << logLine.toStdString() << std::endl;
}

class CppModel: public QAbstractListModel {
    // QAbstractItemModel interface
public:
    virtual int rowCount(const QModelIndex &parent) const override { return 100; }
    virtual QVariant data(const QModelIndex &index,int role) const override {
        if (role == (Qt::DisplayRole + 1)) {
            return QString("Element %1").arg(index.row());
        }
        return QVariant();
    }
    virtual QHash<int,QByteArray> roleNames() const override {
        return {{(Qt::DisplayRole+1),"itemName"}};
    }
};

int main(int argc,char *argv[])
{
    qSetMessagePattern("%{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}");
    qInstallMessageHandler(myMessageHandler);

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc,argv);

    QQmlApplicationEngine engine;
    CppModel cppModel;
    engine.rootContext()->setContextProperty("cppModel",&cppModel);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine,&QQmlApplicationEngine::objectCreated,&app,[url](QObject *obj,const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    },Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

Link to full source code

我做错了什么以及如何正确地为委托元素设置anchors

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)