Qt5 - 在 QML TableView 中显示动态数据模型

dav*_*ler 5 c++ qt qml qt5

我正在为 GUI 开发跟踪窗口。我在 QML 端使用 TableView 元素来显示将不断更新的数据。我怎样才能用数据填充这个元素?元素的数量以及每个元素的数据每隔几毫秒就会发生变化。

我认为信号/插槽实现将是理想的,当数据发生变化时,产生一个信号来触发插槽函数来更新 TableView 中显示的值?沿着这些路线的东西。

提前致谢!

主文件

import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import QtQuick.Dialogs 1.1
import QtQuick 2.1

....
TableView {
                anchors.fill: parent
                id: traceTable
                //table data comes from a model
                model: traceTableModel
                //Component.onCompleted: classInstance.popAndDisplayMsg(classInstance)
                TableViewColumn { role: "index"; title: "Index";  width: 0.25 * mainWindow.width; }
                TableViewColumn { role: "type"; title: "Type"; width: 0.25 * mainWindow.width; }
                TableViewColumn { role: "uid"; title: "ID"; width: 0.25 * mainWindow.width; }
                TableViewColumn { role: "timestamp"; title: "Timestamp"; width: 0.25 * mainWindow.width; }


            }
....
Run Code Online (Sandbox Code Playgroud)

主程序

#include "class_header.hpp"
#include <QtQuick/QQuickView>
#include <QGuiApplication>
#include <QQmlContext>

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

    QQuickView view;

    class_name instance;

    view.rootContext()->setContextProperty("classInstance", &instance);

    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QUrl("qml/main.qml"));
    view.show();
    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

class_header.hpp

#ifndef class_name_HPP
#define class_name_HPP

#include <QtQuick/QQuickItem>
#include <polysync_core.h>
#include <glib.h>
#include <QString>
#include <QDebug>


class class_name : public QQuickItem
{
    Q_OBJECT
    //Maybe some Q_Properties here?

    public:

        //constructor
        class_name(QQuickItem *parent = 0);
        //deconstructor
        ~class_name();

    signals:
        void dataChanged();

    public slots:
        int updateInfo(//pass some data);

};

#endif // class_name_HPP
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 2

您对 QML 模型的使用很奇怪。您不想为每个列使用自定义角色。这毫无意义。您也不需要自定义QQuickItem类。

基本流程是:

  1. QAbstractListModel正确实现从or派生的类QAbstractTableModel

  2. 将此类的实例绑定到 QML 视图的模型。

以下是完整的(如编译和运行中的)参考供您细读: