상세 컨텐츠

본문 제목

[C++ QT QML] C++에서 QML ListView로 값 나타내기

QT|QML

by donggyu1998 2021. 6. 17. 15:30

본문

반응형

💡 실행 사진

💡 main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QAbstractListModel>
#include <QVector>

class ListModel : public QAbstractListModel
{
    Q_OBJECT

public:
    ListModel() {
        for (int i = 0; i < 10; ++i) {
            mContents.append(QString::fromLatin1("Item %1").arg(i));
        }
    }

    int rowCount(const QModelIndex &parent = QModelIndex()) const override {
        Q_UNUSED(parent);
        return mContents.size();
    }

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override {
        Q_UNUSED(role);
        if (!index.isValid() || index.row() < 0 || index.row() >= rowCount())
            return QVariant();

        return mContents.at(index.row());
    }

    Q_INVOKABLE void removeOne() {
        beginRemoveRows(QModelIndex(), rowCount() - 1, rowCount() - 1);
        mContents.takeLast();
        endRemoveRows();
    }

private:
    QVector<QString> mContents;
};

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

    QQmlApplicationEngine engine;
    ListModel model;
    engine.rootContext()->setContextProperty("listModel", &model);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

#include "main.moc"

💡 main.qml

import QtQuick 2.7
import QtQuick.Layouts 1.1
import QtQuick.Window 2.2
import QtQuick.Controls 2.1

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ColumnLayout {
        ListView {
            id: listView
            width: 200
            height: 200
            model: listModel
            currentIndex: 9
            delegate: Rectangle {
                width: 50
                height: 50
                border.width: 1
                Text {
                    text: index
                    anchors.centerIn: parent
                }
            }
        }
    }
}
        RowLayout {
            Button {
                text: "Remove from end"
                onClicked: listView.model.removeOne()
            }
        }
반응형

관련글 더보기