首页 > 解决方案 > QML 连接在新插入的行中不起作用?

问题描述

作为一个例子,我从 Qt Documentation 中取了官方的例子,并添加了几行来演示这个问题:

模型.h:

#include <QAbstractListModel>
#include <QStringList>

//![0]
class Animal
{
public:
    Animal(const QString &type, const QString &size);
//![0]

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;
//![1]
};

class AnimalModel : public QAbstractListModel
{
    Q_OBJECT

    Q_PROPERTY(int myProperty READ myProperty NOTIFY myPropertyChanged)

signals:
    void myPropertyChanged();

public:
    enum AnimalRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AnimalModel(QObject *parent = 0);
//![1]

    void addAnimal(const Animal &animal);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

    // my code starts
    virtual bool insertRows(int position, int rows,
                            const QModelIndex &index = QModelIndex()) override;
    virtual Qt::ItemFlags flags(const QModelIndex &index) const override {
        return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
    }
    int myProperty() const {
        return m_myProperty;
    }
    int m_myProperty;

public slots:
    void addAnimal();
        // my code ends

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Animal> m_animals;
//![2]
};
//![2]

模型.cpp:

#include "model.h"

Animal::Animal(const QString &type, const QString &size)
    : m_type(type), m_size(size)
{
}

QString Animal::type() const
{
    return m_type;
}

QString Animal::size() const
{
    return m_size;
}

AnimalModel::AnimalModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_myProperty(0)
{
}

void AnimalModel::addAnimal(const Animal &animal)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_animals << animal;
    endInsertRows();
}

int AnimalModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_animals.count();
}

QVariant AnimalModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_animals.count())
        return QVariant();

    const Animal &animal = m_animals[index.row()];
    if (role == TypeRole)
        return animal.type();
    else if (role == SizeRole)
        return animal.size();
    return QVariant();
}

bool AnimalModel::insertRows(int position, int rows, const QModelIndex &index)
{
    beginInsertRows(index, position, position + rows - 1);

    for (int row = 0; row < rows; ++row) {
        m_animals.insert(position, Animal("new type", "new animal"));
    }

    endInsertRows();

    return true;
}

void AnimalModel::addAnimal()
{
    insertRow(0);

    m_myProperty = m_animals.count();
    emit myPropertyChanged();
}

//![0]
QHash<int, QByteArray> AnimalModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}
//![0]

最后是 view.qml:

import QtQuick 2.0
import QtQuick.Controls 2.2

//![0]
Column {
    ListView {
        id: list
        width: 200; height: 250

        model: myModel
        delegate: Text {
            text: index + ": Animal: " + type + ", " + size + ", " + list.model.myProperty

            Connections {
                target: myModel
                onMyPropertyChanged: {
                    console.log(index + ", " + list.model.myProperty)
                }
            }
        }
    }
    Button {
        onClicked: {
            myModel.addAnimal()
        }
    }
}

//![0]

很简单。按下按钮并调用后,addAnimal()我希望看到这样的控制台输出:

qml: 0, 4
qml: 1, 4
qml: 2, 4
qml: 3, 4

但相反,我看到了这个:

qml: 1, 4
qml: 2, 4
qml: 3, 4

然而,信号肯定会被发出(和接收),因为 UI 不仅显示新添加的具有更新的动物列表大小的项目,而且所有其他行都已更新。那么为什么新行没有收到onMyPropertyChanged呢?

这是一个Qt错误吗?我正在使用 Qt 5.9.5。

动物列表大小 == 4

标签: c++qtqmlqabstractitemmodel

解决方案


当您使用时,insertRow(0)您将插入位置 0,因此前一个 0 元素现在将成为具有连接并接收信号的元素。

所以最后插入的元素在点击时将没有连接,因此不会被通知。


为了说明,我将逐步解释:

  • 在第一个插入中没有元素,因此没有人接收到信号。

  • 在第二次插入中,前一个 0 元素将是当前 1 并且它具有连接,因此将被通知。

  • 在第三次插入中,前一个 0 元素将是当前 1,前一个元素将是当前 2,因此 1、2 具有连接并将被通知。

总之,委托的创建是在发出myPropertyChanged信号之后,因此插入的委托将不会被通知,其他人会,并且由于您的插入始终位于第一个位置,因此永远不会被打印qml: 0, n

为了以图形方式理解,假设有代表并且他们已经存在,他们将收到通知:

                                            0           0  (+)
0 (+)                                       1  (+)      1  (+)
1 (+)                                       2  (+)      2  (+)
2 (+)                                       3  (+)      3  (+)
... --> clicked --> myPropertyChanged -->  ...     -->  4  (+)
n (+)                                      n+1 (+)     n+1 (+)

(+):表示有连接


更多解释:

需要明确的是,事件循环的规则如下:顺序任务优先执行,对信号的调用如果不紧急则等待。

让我们更详细地分析您的代码:

  1. 插入行(0);
  2. m_myProperty = m_animals.count();
  3. 发出 myPropertyChanged();

前面的行是按顺序执行的,所以在第一步结束时模型中已经有一个新元素,但是视图没有更新,因为为此代码必须返回到事件循环并且它必须完成执行步骤 3。

刚完成第 3 步,信号任务就被执行了,所以你要做的就是创建委托和连接,所以现在你优先考虑myPropertyChanged信号并调用现有的连接减去最后一个,因为它不存在时发出了信号。


总之,只会调用信号发出时存在的槽,不会调用在信号发出后立即创建的新连接,直到槽调用。


推荐阅读