Qt小例子学习89 - 单击qml按钮后通过C++更新TableView

这篇博客介绍了如何在Qt环境中,通过C++与QML的交互来更新TableView的数据。示例中,当用户点击QML中的按钮时,C++的TableModel类会插入新数据,并通知QML界面进行刷新。主要涉及的技术包括QAbstractTableModel、QQmlApplicationEngine、Q_INVOKABLE和QML信号与槽机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Qt小例子学习89 - 单击qml按钮后通过C++更新TableView

TableModel.h

#pragma once

#include <QAbstractTableModel>
#include <QObject>

class TableModel : public QAbstractTableModel
{
    Q_OBJECT
    enum TableRoles { TableDataRole = Qt::UserRole + 1, HeadingRole };
public:
    explicit TableModel(QObject *parent = nullptr) : QAbstractTableModel(parent)
    {
        table.append(
        {
            "First Name",
            "Last Name",
            "Age",
        });
    }
    int rowCount(const QModelIndex & = QModelIndex()) const override
    {
        return table.size();
    }

    int columnCount(const QModelIndex & = QModelIndex()) const override
    {
        return table.at(0).size();
    }

    QVariant data(const QModelIndex &index, int role) const override
    {
        switch (role)
        {
        case TableDataRole:
        {
            return table.at(index.row()).at(index.column());
        }
        case HeadingRole:
        {
            return index.row() == 0;
        }
        default: break;
        }
        return QVariant();
    }
    QHash<int, QByteArray> roleNames() const override
    {
        QHash<int, QByteArray> roles;
        roles[TableDataRole] = "tabledata";
        roles[HeadingRole] = "heading";
        return roles;
    }

    Q_INVOKABLE void addPerson()
    {
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        table.append(
        {
            "Marc",
            "Fonz",
            "25",
        });
        endInsertRows();
    }
private:
    QVector<QVector<QString>> table;
};

MainWindow.h

#pragma once

#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "TableModel.h"

class MainWindow : public QObject
{
    Q_OBJECT
public:
    explicit MainWindow()
    {
        engine_.rootContext()->setContextProperty("myModel", &model_);
        engine_.load(QUrl(QStringLiteral("qrc:/main.qml")));
    }
private:
    TableModel model_;
    QQmlApplicationEngine engine_;
};

main.qml

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

import Qt.labs.settings 1.0
import Qt.labs.platform 1.0 as Platform

import QtQuick.Controls.Material 2.12

ApplicationWindow {
    id: window
    visible: true
    width: 1040
    height: 480
    ColumnLayout{
        spacing: 2
        anchors.fill: parent
        Button {
            text: qsTr("Update List Model")
            onClicked: myModel.addPerson()
        }
        TableView {
            width: 400
            height: 200
            columnSpacing: 1
            rowSpacing: 1
            clip: true
            ScrollIndicator.horizontal: ScrollIndicator { }
            ScrollIndicator.vertical: ScrollIndicator { }
            model: myModel
            delegate: Rectangle {
                implicitWidth: 100
                implicitHeight: 20
                border.color: "black"
                border.width: 2
                color: heading ? 'teal':"green"
                TableView.onPooled: console.log(tabledata + " pooled")
                TableView.onReused: console.log(tabledata + " resused")

                Text {
                    text: tabledata
                    font.pointSize: 10
                    anchors.centerIn: parent
                }
            }
        }
    }
}

main.cpp

#include "MainWindow.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    MainWindow mainwindow;
    return app.exec();
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值