向自定义C ++模型添加行时,QML ListView未更新

时间:2017-03-25 17:33:41

标签: c++ qt qml qt5.8

我为一个频道中存​​在的用户列表实现了我自己的模型。如果模型被填充,数据被读取,那么什么不起作用是实时更新,如果添加了新内容,它显示仅在调整大小事件后才能启动。

bool UserModel::insertUser( QString channelId, QSharedPointer<RocketChatUser> user )
{
    auto values =  userMap.values( channelId );
    int index = values.count();
    auto qIndex = QModelIndex();
    if ( channelId == current ) {
        beginInsertRows( qIndex, index, index );
    }

    userMap.insert( channelId, user );

    if ( channelId == current ) {
        endInsertRows();
    }
}


class UserModel: public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY(QString currentChannel READ getCurrent WRITE setCurrent NOTIFY currentChannelChanged)
    enum UserRoles {
          UserName = Qt::UserRole + 1,
          UserId
      };
public:
    UserModel( QObject *parent = 0 );
    int rowCount( const QModelIndex &parent = QModelIndex() ) const;
    QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const;
    bool insertUser(QString,QSharedPointer<RocketChatUser>);
    QString getCurrent() const;
    void setCurrent(const QString &value);
    void onCurrentChannelChanged(const QString &newText);

protected:
    QHash<int, QByteArray> roleNames() const;
    QSet<QString> duplicateCheck;
    QMultiMap<QString, QSharedPointer<RocketChatUser>> userMap;
    QString current;
signals:
    void currentChannelChanged(const QString &newText);
};

当前频道用于存储多重映射中的所有用户,其密钥是频道的ID,并且出于性能原因仅返回属于该频道的用户。

以这种方式创建:

UserModel userModel;
context->setContextProperty("userModel",&userModel);

QML看起来像这样:

Drawer {
    z: 9
    width: Math.min(window.width, window.height) / 3 * 2
    height: window.height
    edge: Qt.LeftEdge
    ListView {
        anchors.fill: parent
        spacing: 1
        header: ToolBar {
            Text {
                text: qsTr("Users in channel")
                anchors.centerIn: parent
            }
            width: parent.width - 1
        }
        id: userListView
        model: userModel
        delegate: RowLayout {
        width: parent.width
        Button {
            anchors.fill: parent
            text: model.username
        }
        /*BusyIndicator{
                    id: loadingUserIndicator
                                anchors.centerIn: parent
                                        }*/
        }
        Component.onCompleted: {
            userModel.currentChannel = channelView.currentChannel
        }
    }
}

0 个答案:

没有答案