このページでは

TableModel QML Type

シンプルなテーブルモデルをカプセル化しています。詳細...

Import Statement: import Qt.labs.qmlmodels

プロパティ

方法

  • void appendRow(var row)
  • void clear()
  • variant data(QModelIndex index, string role)
  • var getRow(int rowIndex)
  • QModelIndex index(int row, int column)
  • void insertRow(int rowIndex, var row)
  • void moveRow(int fromRowIndex, int toRowIndex, int rows)
  • void removeRow(int rowIndex, int rows)
  • bool setData(QModelIndex index, variant value, string role)
  • void setRow(int rowIndex, var row)

詳細な説明

TableModel型は、TableView で使用可能なテーブルモデルのデータとして、JavaScript/JSONオブジェクトを格納します。これは、C++でカスタムのQAbstractTableModel サブクラスを作成することなく、非常にシンプルなモデルをサポートすることを目的としています。

import QtQuick
import QtQuick.Window
import Qt.labs.qmlmodels

Window {
    width: 400
    height: 400
    visible: true

    TableView {
        anchors.fill: parent
        columnSpacing: 1
        rowSpacing: 1
        boundsBehavior: Flickable.StopAtBounds

        model: TableModel {
            TableModelColumn { display: "checked" }
            TableModelColumn { display: "amount" }
            TableModelColumn { display: "fruitType" }
            TableModelColumn { display: "fruitName" }
            TableModelColumn { display: "fruitPrice" }

            // Each row is one type of fruit that can be ordered
            rows: [
                {
                    // Each property is one cell/column.
                    checked: false,
                    amount: 1,
                    fruitType: "Apple",
                    fruitName: "Granny Smith",
                    fruitPrice: 1.50
                },
                {
                    checked: true,
                    amount: 4,
                    fruitType: "Orange",
                    fruitName: "Navel",
                    fruitPrice: 2.50
                },
                {
                    checked: false,
                    amount: 1,
                    fruitType: "Banana",
                    fruitName: "Cavendish",
                    fruitPrice: 3.50
                }
            ]
        }
        delegate:  TextInput {
            text: model.display
            padding: 12
            selectByMouse: true

            onAccepted: model.display = text

            Rectangle {
                anchors.fill: parent
                color: "#efefef"
                z: -1
            }
        }
    }
}

モデルの初期行データは、rows プロパティを設定するか、appendRow()を呼び出すことで設定されます。モデル内の各列は、TableModelColumn インスタンスを宣言することで指定され、各インスタンスの順序によって列インデックスが決まります。モデルのComponent::completed()シグナルが発行されると、列と役割が確定し、モデルの存続期間中は固定されます。

特定の行にアクセスするには、getRow() 関数を使用できます。また、rows プロパティを介してモデルのJavaScriptデータに直接アクセスすることも可能ですが、この方法ではモデルデータを変更することはできません。

新しい行を追加するには、appendRow() およびinsertRow() を使用します。既存の行を変更するには、setRow()、moveRow()、removeRow()、およびclear() を使用します。

また、上記の例に示すように、デリゲートを介してモデルのデータを変更することも可能です:

        delegate:  TextInput {
            text: model.display
            padding: 12
            selectByMouse: true

            onAccepted: model.display = text

            Rectangle {
                anchors.fill: parent
                color: "#efefef"
                z: -1
            }
        }

変更対象のロールのデータの型が、設定されたデータの型と一致しない場合、QVariant によって自動的に変換されます。

サポートされている行データ構造

TableModelは、各行が単純なキーと値のペアのリストであるJavaScript/JSONデータで動作するように設計されています:

{
    // Each property is one cell/column.
    checked: false,
    amount: 1,
    fruitType: "Apple",
    fruitName: "Granny Smith",
    fruitPrice: 1.50
},
// ...

Qt でのモデル操作は行および列のインデックスを介して行われ、オブジェクトのキーには順序がないため、各列は `TableModelColumn` を通じて指定する必要があります。これにより、Qt の組み込みロールを各行オブジェクトの任意のプロパティにマッピングすることが可能になります。

複雑な行構造もサポートされていますが、機能には制限があります。TableModel は各行の構造を把握する手段を持たないため、それを操作することはできません。 この結果、TableModelがrows に格納しているモデルデータのコピーは、QMLで設定されたソースデータと同期されません。これらの理由から、データの操作はサポートされていません。

たとえば、各行が配列で、各セルがオブジェクトであるデータソースを使用したい場合を考えてみましょう。このデータソースをTableModelで使用するには、次のようなゲッターを定義します:

TableModel {
    TableModelColumn {
        display: function(modelIndex) { return rows[modelIndex.row][0].checked }
    }
    // ...

    rows: [
        [
            { checked: false, checkable: true },
            { amount: 1 },
            { fruitType: "Apple" },
            { fruitName: "Granny Smith" },
            { fruitPrice: 1.50 }
        ]
        // ...
    ]
}

上記の行は、複雑な行の一例です。

注: 複雑な行を使用する場合、appendRow() やremoveRow()などの行操作関数は サポートされません。

TableModel での DelegateChooser の使用

実際のユースケースのほとんどでは、TableModel を使用するTableView のデリゲートとしてDelegateChooser を使用することをお勧めします。これにより、関連するデリゲートで特定のロールを使用できるようになります。たとえば、上記のスニペットは、次のようにDelegateChooser を使用するように書き換えることができます:

import QtQuick
import QtQuick.Controls
import Qt.labs.qmlmodels

ApplicationWindow {
    width: 400
    height: 400
    visible: true

    TableView {
        anchors.fill: parent
        columnSpacing: 1
        rowSpacing: 1
        boundsBehavior: Flickable.StopAtBounds

        model: TableModel {
            TableModelColumn { display: "checked" }
            TableModelColumn { display: "amount" }
            TableModelColumn { display: "fruitType" }
            TableModelColumn { display: "fruitName" }
            TableModelColumn { display: "fruitPrice" }

            // Each row is one type of fruit that can be ordered
            rows: [
                {
                    // Each property is one cell/column.
                    checked: false,
                    amount: 1,
                    fruitType: "Apple",
                    fruitName: "Granny Smith",
                    fruitPrice: 1.50
                },
                {
                    checked: true,
                    amount: 4,
                    fruitType: "Orange",
                    fruitName: "Navel",
                    fruitPrice: 2.50
                },
                {
                    checked: false,
                    amount: 1,
                    fruitType: "Banana",
                    fruitName: "Cavendish",
                    fruitPrice: 3.50
                }
            ]
        }
        delegate: DelegateChooser {
            DelegateChoice {
                column: 0
                delegate: CheckBox {
                    checked: model.display
                    onToggled: model.display = checked
                }
            }
            DelegateChoice {
                column: 1
                delegate: SpinBox {
                    value: model.display
                    onValueModified: model.display = value
                }
            }
            DelegateChoice {
                delegate: TextField {
                    text: model.display
                    selectByMouse: true
                    implicitWidth: 140
                    onAccepted: model.display = text
                }
            }
        }
    }
}

最も具体的なデリゲートが最初に宣言されています。インデックス0 および1 の列は、データ型がbool およびinteger であるため、それぞれCheckBox およびSpinBox を使用します。残りの列は単にTextField を使用できるため、そのデリゲートはフォールバックとして最後に宣言されています。

外部のJSONソースでのTableModelの使用

JSONオブジェクト内のデータの構造がTableModelで定義された構造と一致する場合、rowsプロパティを使用してそのデータをモデルに直接割り当てることができます。データ内のすべての行は、モデルで定義された列に準拠している必要があります。

たとえば、モデルが次のように定義されている場合:

            model: TableModel {
                TableModelColumn { display: "driverId" }
                TableModelColumn { display: "code" }
                TableModelColumn { display: "url" }
                TableModelColumn { display: "givenName" }
                TableModelColumn { display: "familyName" }
                TableModelColumn { display: "dateOfBirth" }
                TableModelColumn { display: "nationality" }
            }

ソースに必要なデータは含まれているものの、必ずしも必要な構造になっていない場合は、データをダウンロードしてモデルが定義する構造に準拠した形式にパースし、その結果を直接割り当てることができます。

    function requestJson() {
        let doc = new XMLHttpRequest()
        doc.onreadystatechange = function() {
            if (doc.readyState === XMLHttpRequest.DONE) {
                var root = JSON.parse(doc.responseText)
                var race = root.MRData.RaceTable.Races[0]
                var raceResults = race.Results
                var drivers = []
                for (let i = 0; i < raceResults.length; ++i) {
                    drivers.push(raceResults[i].Driver)
                }
                tableView.model.rows = drivers
                print(JSON.stringify(drivers))
            }
        }

        doc.open("GET", "https://api.jolpi.ca/ergast/f1/2005/1/results.json")
        doc.send()
    }

その結果を直接割り当てることができます

    Component.onCompleted: requestJson()

また、JavaScript ファイルをモジュールとしてインポートすることで、JSON オブジェクトを指定することもできます。その方法の例については、TreeModel のドキュメントを参照してください。

警告: JSONデータが信頼できるソースから取得されていることを確認してください 。モデルは入力に基づいて行を動的に生成するため、形式が不正なJSONや信頼できないJSONを使用すると、予期しない動作やパフォーマンスの問題を引き起こす可能性があります。

関連項目: TableModelColumn 、TableView 、およびQAbstractTableModel 。

プロパティのドキュメント

columnCount : int [read-only]

この読み取り専用プロパティには、モデルの列数が格納されます。

列数は、rows プロパティが設定された後、またはappendRow()が初めて呼び出された後、モデルの存続期間中は固定されます。

rowCount : int [read-only]

この読み取り専用プロパティは、モデル内の行数を保持します。

この値は、モデルに行が追加または削除されるたびに変化します。

rows : var

このプロパティは、行の配列という形式でモデルデータを保持します:

            rows: [
                {
                    // Each property is one cell/column.
                    checked: false,
                    amount: 1,
                    fruitType: "Apple",
                    fruitName: "Granny Smith",
                    fruitPrice: 1.50
                },
                {
                    checked: true,
                    amount: 4,
                    fruitType: "Orange",
                    fruitName: "Navel",
                    fruitPrice: 2.50
                },
                {
                    checked: false,
                    amount: 1,
                    fruitType: "Banana",
                    fruitName: "Cavendish",
                    fruitPrice: 3.50
                }
            ]

関連項目: getRow(),setRow(),moveRow(),appendRow(),insertRow(),clear(),rowCount およびcolumnCount 。

メソッドのドキュメント

void appendRow(var row)

モデルの末尾に、row にある値(セル)を含む新しい行を追加します。

model.appendRow({
    checkable: true,
    amount: 1,
    fruitType: "Pear",
    fruitName: "Williams",
    fruitPrice: 1.50,
})

insertRow()、setRow()、およびremoveRow()も参照してください 。

void clear()

モデルからすべての行を削除します。

removeRow()も参照してください 。

variant data(QModelIndex index, string role)

指定されたindex に位置する、指定されたrole に属するテーブルセルのデータを返します。

index() およびsetData()も参照してください 。

var getRow(int rowIndex)

モデル内のrowIndex にある行を返します。

これは、rows プロパティを通じて行に直接アクセスすることと同等であることに注意してください:

Component.onCompleted: {
    // These two lines are equivalent.
    console.log(model.getRow(0).display);
    console.log(model.rows[0].fruitName);
}

注:返されたオブジェクトを使用して モデルの内容を変更することはできません。その場合は、代わりに `setRow()` を使用してください。

関連項目: setRow()、appendRow()、insertRow()、removeRow()、およびmoveRow()。

QModelIndex index(int row, int column)

指定されたrow およびcolumn を参照するQModelIndex オブジェクトを返します。このオブジェクトをdata()関数に渡すと、そのセルからデータを取得でき、setData()に渡すと、そのセルの内容を編集できます。

import QtQml 2.14
import Qt.labs.qmlmodels 1.0

TableModel {
    id: model

    TableModelColumn { display: "fruitType" }
    TableModelColumn { display: "fruitPrice" }

    rows: [
        { fruitType: "Apple", fruitPrice: 1.50 },
        { fruitType: "Orange", fruitPrice: 2.50 }
    ]

    Component.onCompleted: {
        for (var r = 0; r < model.rowCount; ++r) {
            console.log("An " + model.data(model.index(r, 0)).display +
                        " costs " + model.data(model.index(r, 1)).display.toFixed(2))
        }
    }
}

QModelIndex および QML の関連クラス、ならびに `data()`も参照してください 。

void insertRow(int rowIndex, var row)

rowIndex の位置に、row に指定された値(セル)を持つ新しい行をモデルに追加します。

model.insertRow(2, {
    checkable: true, checked: false,
    amount: 1,
    fruitType: "Pear",
    fruitName: "Williams",
    fruitPrice: 1.50,
})

rowIndex は、テーブル内の既存の項目、またはテーブルの末尾を1つ越えた位置を指す必要があります(これはappendRow() と同等です)。

appendRow()、setRow()、removeRow()、およびrowCountも参照してください 。

void moveRow(int fromRowIndex, int toRowIndex, int rows)

rows を、インデックスfromRowIndex からインデックスtoRowIndex に移動します。

「from」および「to」の範囲は存在している必要があります。たとえば、最初の 3 つの項目をリストの末尾に移動するには、次のようにします。

model.moveRow(0, model.rowCount - 3, 3)

appendRow()、insertRow()、removeRow()、およびrowCountも参照してください 。

void removeRow(int rowIndex, int rows = 1)

rowIndex にある複数の「rows 」をモデルから削除します。

clear() およびrowCountも参照してください 。

bool setData(QModelIndex index, variant value, string role)

role で指定されたデータフィールドを、index で指定されたテーブルセルに、value を使用して挿入または更新します。成功した場合は true を、失敗した場合は false を返します。

data() およびindex()も参照してください 。

void setRow(int rowIndex, var row)

モデル内のrowIndex にある行を、row に変更します。

row には、すべての列およびセルが含まれており、かつ正しい順序で並んでいる必要があります。

model.setRow(0, {
    checkable: true,
    amount: 1,
    fruitType: "Pear",
    fruitName: "Williams",
    fruitPrice: 1.50,
})

rowIndex がrowCount() と等しい場合、モデルに新しい行が追加されます。そうでない場合、rowIndex はモデル内の既存の行を指している必要があります。

appendRow()、insertRow()、およびrowCountも参照してください 。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.