본문 바로가기
Qt

QML + QAbstractTableModel 예제

by 서스틴 2023. 9. 19.

QML + QAbstractTableModel 예제 

//tablemodel.h

class usrDefineType 
{
public:
//기본생성자
//기본 소멸자
//기본 복사생성자
//기본 대입연산자
	int a;
    Qchar b;
    QString c;
    bool d;
}


class TableModel : public QAbstractTableModel
{
	Q_OBJECT

public:
	enum ColumnName {
    	id = Qt::UserRole,
        type,
        Data,
        status
    };

	explicit TableModel();
    //필수적으로 override.
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;  
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    
private:
	QList<usrDefineType> _list; //사용자 정의 타입도 넣을 수 있다. 
}

//tablemodel.cpp
#include "tablemodel.h"

TableModel::TableModel()
{
//테스트하고싶은 데이터를 _list에 append 해주어도 된다. 
}

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

int TableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 4; //column 숫자를 넣어주면됨

}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    Q_UNUSED(role)
    QVariant value;

    switch (role) {
    case id : value = _list.at(index.row()).a; break;
    case type: value = _list.at(index.row()).b; break;
    case Data: value = _list.at(index.row()).c; break;
    case status: value = _list.at(index.row()).d; break;
    default: break;
    }
    return value;

}

QHash<int, QByteArray> TableModel::roleNames() const
{
    static QHash<int, QByteArray> roles;
    roles[id] = "Identifier";
    roles[type] = "Type";
    roles[Data] = "Data";
    roles[status] = "Status";
    return roles;
}

기본적인 tablemodel을 override 해준다.

MainClass에 객체로 넣어주기

#include <QObject>
#include <tablemodel.h>

class MainClass : public QObject
{
    Q_OBJECT

    //QML에서 사용할 모델을 프로퍼티로 만들어준다.
    Q_PROPERTY(TableModel *tablemodel READ getTableModel NOTIFY tablemodelChanged) // ---3

public:
    explicit MainClass(QObject *parent = nullptr);

    TableModel* getTableModel() { return &m_tableModel;} //----2

signals:
    void tablemodelChanged(); //---4

private:
    TableModel m_tableModel; //-----1
};

Main.cpp 에서 클래스와 QML 이어주기

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <mainclass.h>

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType<MainClass>("MainClass", 1,0,"MainClass");


    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 1.4
import MainClass 1.0
import QtQuick.Layouts 1.2

ApplicationWindow
{
    id : root
    visible: true
    width: 1280
    height: 720
    title: qsTr("TableVIEW")

    MainClass {id: myMainClass}

    TableView {
        id: myTableView
        anchors.fill: parent
        model: myMainClass.tablemodel

        TableViewColumn {
            role:"Identifier"
            title:"ID"
            width: myTableView.width/4
        }

        TableViewColumn {
            role:"Type"
            title:"Type"
            width: myTableView.width/4
        }

        TableViewColumn {
            role:"Data"
            title:"Data"
            width: myTableView.width/4
        }

        TableViewColumn {
            role:"Status"
            title:"Status"
            width: myTableView.width/4
        }
    }
}

결과 

완성된 테이블 뷰

테스트 

TableModel::TableModel()
{
    usrDefineType usr;
    usr.a = 1;
    usr.b = 'a';
    usr.c = "myData";
    usr.d = false;

    _list.append(usr);
}

테이블 뷰 테스트

 

'Qt' 카테고리의 다른 글

ProgressBar 커스텀하기  (0) 2023.09.25