草庐IT

c++ - 将新项目添加到基于 QAbstractListModel 的模型时,QML View 不会更新

coder 2024-02-08 原文

我已经弄清楚如何将派生自 QAbstractListModel 的模型绑定(bind)到 QML View 。

但是接下来我累了就不行了。如果将新项目添加到模型,QML View 将不会更新。这是为什么?

DataObject.h

class DataObject {
    public:
        DataObject(const QString &firstName,
                   const QString &lastName):
            first(firstName),
            last(lastName) {}

        QString first;
        QString last;
};

SimpleListModel.h

class SimpleListModel : public QAbstractListModel
{
    Q_OBJECT

    enum /*class*/ Roles {
        FIRST_NAME = Qt::UserRole,
        LAST_NAME
    };

    public:
        SimpleListModel(QObject *parent=0);
        QVariant data(const QModelIndex &index, int role) const;
        Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const;
        QHash<int, QByteArray> roleNames() const;
        void addName(QString firstName, QString lastName);

    private:
        Q_DISABLE_COPY(SimpleListModel);
        QList<DataObject*> m_items;
};

SimpleListModel.cpp

SimpleListModel::SimpleListModel(QObject *parent) :
    QAbstractListModel(parent)
{
    DataObject *first = new DataObject(QString("Firstname01"), QString("Lastname01"));
    DataObject *second = new DataObject(QString("Firstname02"), QString("Lastname02"));
    DataObject *third = new DataObject(QString("Firstname03"), QString("Lastname03"));

    m_items.append(first);
    m_items.append(second);
    m_items.append(third);
}

QHash<int, QByteArray> SimpleListModel::roleNames() const
{
    QHash<int, QByteArray> roles;

    roles[/*Roles::*/FIRST_NAME] = "firstName";
    roles[/*Roles::*/LAST_NAME] = "lastName";

    return roles;
}

void SimpleListModel::addName(QString firstName, QString lastName)
{
    DataObject *dataObject = new DataObject(firstName, lastName);

    m_items.append(dataObject);

    emit dataChanged(this->index(m_items.size()), this->index(m_items.size()));
}

int SimpleListModel::rowCount(const QModelIndex &) const
{
    return m_items.size();
}

QVariant SimpleListModel::data(const QModelIndex &index, int role) const
{
    //--- Return Null variant if index is invalid
    if(!index.isValid())
        return QVariant();

    //--- Check bounds
    if(index.row() > (m_items.size() - 1))
        return QVariant();

    DataObject *dobj = m_items.at(index.row());

    switch (role)
    {
        case /*Roles::*/FIRST_NAME:
            return QVariant::fromValue(dobj->first);

        case /*Roles::*/LAST_NAME:
            return QVariant::fromValue(dobj->last);

        default:
            return QVariant();
    }
}

AppCore.h

class AppCore : public QObject
{
    Q_OBJECT
    Q_PROPERTY(SimpleListModel *simpleListModel READ simpleListModel CONSTANT)

    public:
        explicit AppCore(QObject *parent = 0);
        SimpleListModel *simpleListModel() const;

    public slots:
        void addName();

    private:
        SimpleListModel *m_SimpleListModel;

};

AppCore.cpp

AppCore::AppCore(QObject *parent) :
    QObject(parent)
{
    m_SimpleListModel = new SimpleListModel(this);
}

SimpleListModel *AppCore::simpleListModel() const
{
    return m_SimpleListModel;
}

void AppCore::addName()
{
    m_SimpleListModel->addName("FirstnameNEW", "LastnameNEW");
}

main.cpp

int main(int argc, char *argv[])
{
    QGuiApplication a(argc, argv);

    QQuickView *view = new QQuickView();
    AppCore *appCore = new AppCore();

    qRegisterMetaType<SimpleListModel *>("SimpleListModel");

    view->engine()->rootContext()->setContextProperty("appCore", appCore);
    view->setSource(QUrl::fromLocalFile("main.qml"));
    view->show();

    return a.exec();
}

ma​​in.qml

// ...
ListView {
    id: myListView
    anchors.fill: parent
    delegate: myDelegate
    model: appCore.simpleListModel
}

MouseArea {
    anchors.fill: parent
    onClicked: {
        appCore.addName()
        console.log('rowCount: ' + appCore.simpleListModel.rowCount())
    }
}
//...

最佳答案

你应该调用 beginInsertRowsendInsertRows 而不是发出信号

void SimpleListModel::addName(QString firstName, QString lastName)
{
    DataObject *dataObject = new DataObject(firstName, lastName);

    // tell QT what you will be doing
    beginInsertRows(ModelIndex(),m_items.size(),m_items.size());

    // do it
    m_items.append(dataObject);

    // tell QT you are done
    endInsertRows();

}

这两个函数发出所有需要的信号

关于c++ - 将新项目添加到基于 QAbstractListModel 的模型时,QML View 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829285/

有关c++ - 将新项目添加到基于 QAbstractListModel 的模型时,QML View 不会更新的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  5. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  6. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  7. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  8. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  9. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  10. 叮咚买菜基于 Apache Doris 统一 OLAP 引擎的应用实践 - 2

    导读:随着叮咚买菜业务的发展,不同的业务场景对数据分析提出了不同的需求,他们希望引入一款实时OLAP数据库,构建一个灵活的多维实时查询和分析的平台,统一数据的接入和查询方案,解决各业务线对数据高效实时查询和精细化运营的需求。经过调研选型,最终引入ApacheDoris作为最终的OLAP分析引擎,Doris作为核心的OLAP引擎支持复杂地分析操作、提供多维的数据视图,在叮咚买菜数十个业务场景中广泛应用。作者|叮咚买菜资深数据工程师韩青叮咚买菜创立于2017年5月,是一家专注美好食物的创业公司。叮咚买菜专注吃的事业,为满足更多人“想吃什么”而努力,通过美好食材的供应、美好滋味的开发以及美食品牌的孵

随机推荐