Provides a table view of items to display data from a model. 更多...
import 语句: | import QtQuick |
继承: | |
继承者: |
(从 6.4 起)
(从 6.5 起)
(从 6.4 起)
(从 6.4 起)
(从 6.5 起)
(从 6.5 起)
(从 6.4 起)
(从 6.6 起)
(从 6.2 起)
(从 6.5 起)
(从 6.4 起)
(从 6.5 起)
(从 6.4 起)
(从 6.2 起)
(从 6.5 起)
(从 6.2 起)
(从 6.2 起)
(since 6.4.3)
(从 6.2 起)
(从 6.2 起)
(从 6.5 起)
(从 6.4 起)
(从 6.5 起)
(从 6.4 起)
(从 6.2 起)
A TableView has a model that defines the data to be displayed, and a delegate that defines how the data should be displayed.
TableView inherits Flickable . This means that while the model can have any number of rows and columns, only a subsection of the table is usually visible inside the viewport. As soon as you flick, new rows and columns enter the viewport, while old ones exit and are removed from the viewport. The rows and columns that move out are reused for building the rows and columns that move into the viewport. As such, the TableView support models of any size without affecting performance.
A TableView displays data from models created from built-in QML types such as ListModel and XmlListModel , which populates the first column only in a TableView. To create models with multiple columns, either use TableModel or a C++ model that inherits QAbstractItemModel .
A TableView does not include headers by default. You can add headers using the HorizontalHeaderView and VerticalHeaderView from Qt Quick Controls.
注意: TableView will only load as many delegate items as needed to fill up the view. There is no guarantee that items outside the view will be loaded, although TableView will sometimes pre-load items for optimization reasons. Hence, a TableView with zero width or height might not load any delegate items at all.
The following example shows how to create a model from C++ with multiple columns:
#include <qqml.h> #include <QAbstractTableModel> class TableModel : public QAbstractTableModel { Q_OBJECT QML_ELEMENT QML_ADDED_IN_VERSION(1, 1) public: int rowCount(const QModelIndex & = QModelIndex()) const override { return 200; } int columnCount(const QModelIndex & = QModelIndex()) const override { return 200; } QVariant data(const QModelIndex &index, int role) const override { switch (role) { case Qt::DisplayRole: return QString("%1, %2").arg(index.column()).arg(index.row()); default: break; } return QVariant(); } QHash<int, QByteArray> roleNames() const override { return { {Qt::DisplayRole, "display"} }; } };
And then how to use it from QML:
import QtQuick import TableModel 0.1 TableView { anchors.fill: parent columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel {} delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 Text { text: display } } }
For prototyping and displaying very simple data (from a web API, for example), TableModel 可以被使用:
import QtQuick import Qt.labs.qmlmodels TableView { anchors.fill: parent columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel { TableModelColumn { display: "name" } TableModelColumn { display: "color" } rows: [ { "name": "cat", "color": "black" }, { "name": "dog", "color": "brown" }, { "name": "bird", "color": "white" } ] } delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 border.width: 1 Text { text: display anchors.centerIn: parent } } }
TableView recycles delegate items by default, instead of instantiating from the delegate whenever new rows and columns are flicked into view. This approach gives a huge performance boost, depending on the complexity of the delegate.
When an item is flicked out, it moves to the reuse pool , which is an internal cache of unused items. When this happens, the TableView::pooled signal is emitted to inform the item about it. Likewise, when the item is moved back from the pool, the TableView::reused 信号发射。
Any item properties that come from the model are updated when the item is reused. This includes
index
,
row
,和
column
, but also any model roles.
注意: Avoid storing any state inside a delegate. If you do, reset it manually on receiving the TableView::reused 信号。
If an item has timers or animations, consider pausing them on receiving the TableView::pooled signal. That way you avoid using the CPU resources for items that are not visible. Likewise, if an item has resources that cannot be reused, they could be freed up.
If you don't want to reuse items or if the
delegate
cannot support it, you can set the
reuseItems
特性到
false
.
注意: While an item is in the pool, it might still be alive and respond to connected signals and bindings.
The following example shows a delegate that animates a spinning rectangle. When it is pooled, the animation is temporarily paused:
Component { id: tableViewDelegate Rectangle { implicitWidth: 100 implicitHeight: 50 TableView.onPooled: rotationAnimation.pause() TableView.onReused: rotationAnimation.resume() Rectangle { id: rect anchors.centerIn: parent width: 40 height: 5 color: "green" RotationAnimation { id: rotationAnimation target: rect duration: (Math.random() * 2000) + 200 from: 0 to: 359 running: true loops: Animation.Infinite } } } }
When a new column is flicked into view, TableView will determine its width by calling the
columnWidthProvider
. If set, this function will alone decide the width of the column. Otherwise, it will check if an explicit width has been set with
setColumnWidth
(). If not,
implicitColumnWidth
() will be used. The implicit width of a column is the same as the largest
implicit width
found among the currently loaded delegate items in that column. Trying to set an explicit
width
directly on a delegate has no effect, and will be ignored and overwritten. The same logic also applies to row heights.
An implementation of a columnWidthProvider that is equivalent to the default logic would be:
columnWidthProvider: function(column) { let w = explicitColumnWidth(column) if (w >= 0) return w; return implicitColumnWidth(column) }
Once the column width is resolved, all other items in the same column are resized to this width, including any items that are flicked into the view at a later point.
注意:
The resolved width of a column is discarded when the whole column is flicked out of the view, and is recalculated again if it's flicked back in. This means that if the width depends on the
implicitColumnWidth
(), the calculation can be different each time, depending on which row you're at when the column enters (since
implicitColumnWidth
() only considers the delegate items that are currently
loaded
). To avoid this, you should use a
columnWidthProvider
, or ensure that all the delegate items in the same column have the same
implicitWidth
.
If you change the values that a rowHeightProvider 或 columnWidthProvider return for rows and columns inside the viewport, you must call forceLayout . This informs TableView that it needs to use the provider functions again to recalculate and update the layout.
Since Qt 5.13, if you want to hide a specific column, you can return
0
从
columnWidthProvider
for that column. Likewise, you can return 0 from the
rowHeightProvider
to hide a row. If you return a negative number, TableView will fall back to calculate the size based on the delegate items.
注意: The size of a row or column should be a whole number to avoid sub-pixel alignment of items.
The following example shows how to set a simple
columnWidthProvider
together with a timer that modifies the values the function returns. When the array is modified,
forceLayout
is called to let the changes take effect:
TableView { id: tableView property var columnWidths: [100, 50, 80, 150] columnWidthProvider: function (column) { return columnWidths[column] } Timer { running: true interval: 2000 onTriggered: { tableView.columnWidths[2] = 150 tableView.forceLayout(); } } }
You can let the user edit table cells by providing an edit delegate. The edit delegate will be instantiated according to the editTriggers , which by default is when the user double taps on a cell, or presses e.g Qt::Key_Enter or Qt::Key_Return . The edit delegate is set using TableView::editDelegate , which is an attached property that you set on the delegate . The following snippet shows how to do that:
TableView { id: tableView anchors.fill: parent clip: true model: TableModel { TableModelColumn { display: "name" } rows: [ { "name": "Harry" }, { "name": "Hedwig" } ] } selectionModel: ItemSelectionModel {} delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 Text { anchors.centerIn: parent text: display } TableView.editDelegate: TextField { anchors.fill: parent text: display horizontalAlignment: TextInput.AlignHCenter verticalAlignment: TextInput.AlignVCenter Component.onCompleted: selectAll() TableView.onCommit: { display = text // 'display = text' is short-hand for: // let index = TableView.view.index(row, column) // TableView.view.model.setData(index, text, Qt.DisplayRole) } } } }
If the user presses Qt::Key_Enter or Qt::Key_Return while the edit delegate is active, TableView will emit the TableView::commit signal to the edit delegate, so that it can write back the changed data to the model.
注意:
In order for a cell to be editable, the model needs to override
QAbstractItemModel::flags
(), and return
Qt::ItemIsEditable
. This flag is not enabled in
QAbstractItemModel
by default. The override could for example look like this:
Qt::ItemFlags QAbstractItemModelSubClass::flags(const QModelIndex &index) const override { Q_UNUSED(index) return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable; }
若
TableView delegate
has a property
required property bool editing
defined, it will be set to
true
for the delegate being edited. See the documentation for
editDelegate
for an example on how to use it.
All new items that are instantiated from the delegate are parented to the
contentItem
采用
z
值,
1
. You can add your own items inside the Tableview, as child items of the Flickable. By controlling their
z
value, you can make them be on top of or underneath the table items.
Here is an example that shows how to add some text on top of the table, that moves together with the table as you flick:
TableView { id: tableView topMargin: header.implicitHeight Text { id: header text: "A table header" } }
Here is another example that shows how to create an overlay item that stays on top of a particular cell. This requires a bit more code, since the location of a cell will change if the user, for example, is resizing a column in front of it.
Rectangle { id: overlay width: 20 height: 20 radius: 10 color: "blue" z: 10 parent: tableView.contentItem Connections { target: tableView function onLayoutChanged() { let item = tableView.itemAtCell(5, 5) let insideViewport = item !== null overlay.visible = insideViewport if (insideViewport) { overlay.x = item.x overlay.y = item.y } } } }
You could also parent the overlay directly to the cell instead of the contentItem . But doing so will be fragile since the cell is unloaded or reused whenever it's flicked out of the viewport.
You can add selection support to TableView by assigning an ItemSelectionModel 到 selectionModel property. It will then use this model to control which delegate items should be shown as selected, and which item should be shown as current. You can set selectionBehavior to control if the user should be allowed to select individual cells, rows, or columns.
To find out whether a delegate is selected or current, declare the following properties:
delegate: Item { required property bool selected required property bool current // ... }
注意:
the
selected
and
current
properties must be defined as
required
. This will inform TableView that it should take responsibility for updating their values. If not, they will simply be ignored. See also
Required Properties
.
The following snippet shows how an application can render the delegate differently depending on the
selected
特性:
TableView { id: tableView anchors.fill: parent clip: true model: TableModel { TableModelColumn { display: "name" } rows: [ { "name": "Harry" }, { "name": "Hedwig" } ] } selectionModel: ItemSelectionModel {} delegate: Rectangle { implicitWidth: 100 implicitHeight: 30 color: selected ? "blue" : "lightgray" required property bool selected Text { text: display } } }
The currentRow and currentColumn properties can also be useful if you need to render a delegate differently depending on if it lies on the same row or column as the current item.
注意: Qt Quick Controls offers a SelectionRectangle that can be used to let the user select cells.
注意:
By default, a cell will become
current
, and any selections will be removed, when the user taps on it. If such default tap behavior is not wanted (e.g if you use custom pointer handlers inside your delegate), you can set
pointerNavigationEnabled
to
false
.
In order to support keyboard navigation, you need to assign an ItemSelectionModel 到 selectionModel property. TableView will then use this model to manipulate the model's currentIndex .
It's the responsibility of the delegate to render itself as
current
. You can do this by adding a property
required property bool current
to it, and let the appearance depend on its state. The
current
property's value is set by the TableView. You can also disable keyboard navigation fully (in case you want to implement your own key handlers) by setting
keyNavigationEnabled
to
false
.
The following example demonstrates how you can use keyboard navigation together with
current
and
selected
properties:
ApplicationWindow { width: 800 height: 600 visible: true ScrollView { anchors.fill: parent TableView { id: tableView clip: true interactive: true rowSpacing: 1 columnSpacing: 1 model: TableModel { TableModelColumn { display: "checked" } TableModelColumn { display: "amount" } TableModelColumn { display: "fruitType" } TableModelColumn { display: "fruitName" } TableModelColumn { display: "fruitPrice" } rows: [ { 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 } ] } selectionModel: ItemSelectionModel {} delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 required property bool selected required property bool current border.width: current ? 2 : 0 color: selected ? "lightblue" : palette.base Text{ text: model.display padding: 12 } } } } SelectionRectangle { target: tableView } }
Implementing copy and paste operations for a TableView usually also includes using a QUndoStack (or some other undo/redo framework). The QUndoStack can be used to store the different operations done on the model, like adding or removing rows, or pasting data from the clipboard, with a way to undo it again later. However, an accompanying QUndoStack that describes the possible operations, and how to undo them, should be designed according to the needs of the model and the application. As such, TableView doesn't offer a built-in API for handling copy and paste.
The following snippet can be used as a reference for how to add copy and paste support to your model and TableView. It uses the existing mime data API in QAbstractItemModel , together with QClipboard . The snippet will work as it is, but can also be extended to use a QUndoStack .
// Inside your C++ QAbstractTableModel subclass: Q_INVOKABLE void copyToClipboard(const QModelIndexList &indexes) const { QGuiApplication::clipboard()->setMimeData(mimeData(indexes)); } Q_INVOKABLE bool pasteFromClipboard(const QModelIndex &targetIndex) { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(); // Consider using a QUndoCommand for the following call. It should store // the (mime) data for the model items that are about to be overwritten, so // that a later call to undo can revert it. return dropMimeData(mimeData, Qt::CopyAction, -1, -1, targetIndex); }
The two functions can, for example, be used from QML like this:
TableView { id: tableView model: tableModel selectionModel: ItemSelectionModel {} Shortcut { sequence: StandardKey.Copy onActivated: { let indexes = tableView.selectionModel.selectedIndexes tableView.model.copyToClipboard(indexes) } } Shortcut { sequence: StandardKey.Paste onActivated: { let targetIndex = tableView.selectionModel.currentIndex tableView.model.pasteFromClipboard(targetIndex) } } }
另请参阅 TableView::editDelegate , TableView::commit , editTriggers , edit (), closeEditor (), layoutChanged (), QAbstractItemModel::mimeData (), QAbstractItemModel::dropMimeData (), QUndoStack , QUndoCommand ,和 QClipboard .
alternatingRows : bool |
This property controls whether the background color of the rows should alternate. The default value is style dependent.
注意:
This property is only a hint, and might therefore not be respected by custom delegates. It's recommended that a delegate alternates between
palette.base
and
palette.alternateBase
when this hint is
true
, so that the colors can be set from outside of the delegate. For example:
background: Rectangle { color: control.row === control.tableView.currentRow ? control.palette.highlight : (control.tableView.alternatingRows && control.row % 2 !== 0 ? control.palette.alternateBase : control.palette.base) }
animate
:
bool
|
This property can be set to control if
TableView
should animate the
contentItem
(
contentX
and
contentY
). It is used by
positionViewAtCell
(), and when navigating
the current index
with the keyboard. The default value is
true
.
若设为
false
, any ongoing animation will immediately stop.
注意:
This property is only a hint.
TableView
might choose to position the content item without an animation if, for example, the target cell is not
loaded
. However, if set to
false
, animations will always be off.
该特性在 Qt 6.4 引入。
另请参阅 positionViewAtCell ().
bottomRow : int |
This property holds the bottom-most row that is currently visible inside the view.
另请参阅 leftColumn , rightColumn ,和 topRow .
columnSpacing : real |
This property holds the spacing between the columns.
默认值为
0
.
columnWidthProvider : var |
This property can hold a function that returns the column width for each column in the model. It is called whenever
TableView
needs to know the width of a specific column. The function takes one argument,
column
, for which the
TableView
needs to know the width.
Since Qt 5.13, if you want to hide a specific column, you can return
0
width for that column. If you return a negative number,
TableView
calculates the width based on the delegate items.
注意: The columnWidthProvider will usually be called two times when a column is about to load (or when doing layout). First, to know if the column is visible and should be loaded. And second, to determine the width of the column after all items have been loaded. If you need to calculate the column width based on the size of the delegate items, you need to wait for the second call, when all the items have been loaded. You can check for this by calling isColumnLoaded (column), and simply return -1 if that is not yet the case.
另请参阅 rowHeightProvider , isColumnLoaded (),和 Row heights and column widths .
columns
:
int
|
This property holds the number of columns in the table.
注意: columns is usually equal to the number of columns in the model, but can temporarily differ until all pending model changes have been processed.
If the model is a list, columns will be
1
.
This property is read only.
contentHeight : real |
This property holds the table height required to accommodate the number of rows in the data model. This is usually not the same as the
height
的
view
, which means that the table's height could be larger or smaller than the viewport height. As a
TableView
cannot always know the exact height of the table without loading all rows in the model, the
contentHeight
is usually an estimate based on the initially loaded table.
If you know what the height of the table will be, assign a value to
contentHeight
, to avoid unnecessary calculations and updates to the
TableView
.
另请参阅 contentWidth and rowHeightProvider .
contentWidth : real |
This property holds the table width required to accommodate the number of columns in the model. This is usually not the same as the
width
的
view
, which means that the table's width could be larger or smaller than the viewport width. As a
TableView
cannot always know the exact width of the table without loading all columns in the model, the
contentWidth
is usually an estimate based on the initially loaded table.
If you know what the width of the table will be, assign a value to
contentWidth
, to avoid unnecessary calculations and updates to the
TableView
.
另请参阅 contentHeight and columnWidthProvider .
currentColumn
:
int
|
This read-only property holds the column in the view that contains the item that is
current.
If no item is current, it will be
-1
.
注意: In order for TableView to report what the current column is, you need to assign an ItemSelectionModel to selectionModel .
另请参阅 currentRow , selectionModel ,和 选择项 .
currentRow
:
int
|
This read-only property holds the row in the view that contains the item that is
current.
If no item is current, it will be
-1
.
注意: In order for TableView to report what the current row is, you need to assign an ItemSelectionModel to selectionModel .
另请参阅 currentColumn , selectionModel ,和 选择项 .
delegate : 组件 |
The delegate provides a template defining each cell item instantiated by the view. The model index is exposed as an accessible
index
property. The same applies to
row
and
column
. Properties of the model are also available depending upon the type of
Data Model
.
A delegate should specify its size using implicitWidth and implicitHeight 。 TableView lays out the items based on that information. Explicit width or height settings are ignored and overwritten.
Inside the delegate, you can optionally add one or more of the following properties. TableView modifies the values of these properties to inform the delegate which state it's in. This can be used by the delegate to render itself differently according on its own state.
true
if the delegate is
current.
true
if the delegate is
selected.
true
if the delegate is being
edited.
The following example shows how to use these properties:
delegate: Rectangle { required property bool current required property bool selected border.width: current ? 1 : 0 color: selected ? palette.highlight : palette.base }
注意:
Delegates are instantiated as needed and may be destroyed at any time. They are also reused if the
reuseItems
property is set to
true
. You should therefore avoid storing state information in the delegates.
另请参阅 Row heights and column widths , Reusing items ,和 Required Properties .
editTriggers
:
enumeration
|
This property holds the different ways the user can start to edit a cell. It can be a combination of the following values:
常量 | 描述 |
---|---|
TableView.NoEditTriggers
|
- the user cannot trigger editing of cells. When this value is set, TableView will neither open or close the edit delegate as a response to any user interaction. But the application can call edit () 和 closeEditor () manually. |
TableView.SingleTapped
|
- the user can edit a cell by single tapping it. |
TableView.DoubleTapped
|
- the user can edit a cell by double tapping it. |
TableView.SelectedTapped
|
- the user can edit a selected cell by tapping it. |
TableView.EditKeyPressed
|
- the user can edit the
current cell
by pressing one of the edit keys. The edit keys are decided by the OS, but are normally
Qt::Key_Enter
and
Qt::Key_Return
.
|
TableView.AnyKeyPressed
|
- the user can edit the current cell by pressing any key, other than the cell navigation keys. The pressed key is also sent to the focus object inside the edit delegate . |
For
TableView.SelectedTapped
,
TableView.EditKeyPressed
,和
TableView.AnyKeyPressed
to have any effect,
TableView
needs to have a
selection model
assigned, since they depend on a
current index
being set. To be able to receive any key events at all,
TableView
will also need to have
QQuickItem::activeFocus
.
When editing a cell, the user can press
Qt::Key_Tab
or
Qt::Key_Backtab
to
commit
the data, and move editing to the next cell. This behavior can be disabled by setting
QQuickItem::activeFocusOnTab
on
TableView
to
false
.
注意:
In order for a cell to be editable, the
delegate
needs an
edit delegate
attached, and the model needs to return
Qt::ItemIsEditable
from
QAbstractItemModel::flags
() (exemplified underneath). If you still cannot edit a cell after activating one of the specified triggers, you can, as a help, try to call
edit
() explicitly (e.g from a Button/
TapHandler
). Doing so will print out a warning explaining why the cell cannot be edited.
Qt::ItemFlags QAbstractItemModelSubClass::flags(const QModelIndex &index) const override { Q_UNUSED(index) return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable; }
该特性在 Qt 6.5 引入。
另请参阅 TableView::editDelegate , TableView::commit ,和 Editing cells .
keyNavigationEnabled
:
bool
|
This property can be set to control if the user should be able to change
the current index
using the keyboard. The default value is
true
.
注意: In order for TableView to support keyboard navigation, you need to assign an ItemSelectionModel to selectionModel .
该特性在 Qt 6.4 引入。
另请参阅 Keyboard navigation , selectionModel , selectionBehavior , pointerNavigationEnabled ,和 interactive .
leftColumn : int |
This property holds the leftmost column that is currently visible inside the view.
另请参阅 rightColumn , topRow ,和 bottomRow .
model : model |
This property holds the model that provides data for the table.
The model provides the set of data that is used to create the items in the view. Models can be created directly in QML using TableModel , ListModel , ObjectModel , or provided by a custom C++ model class. The C++ model must be a subclass of QAbstractItemModel or a simple list.
另请参阅 数据模型 .
pointerNavigationEnabled
:
bool
|
This property can be set to control if the user should be able to change
the current index
using mouse or touch. The default value is
true
.
该特性在 Qt 6.4 引入。
另请参阅 selectionModel , keyNavigationEnabled ,和 interactive .
resizableColumns
:
bool
|
This property holds whether the user is allowed to resize columns by dragging between the cells. The default value is
false
.
该特性在 Qt 6.5 引入。
resizableRows
:
bool
|
This property holds whether the user is allowed to resize rows by dragging between the cells. The default value is
false
.
该特性在 Qt 6.5 引入。
reuseItems : bool |
This property holds whether or not items instantiated from the
delegate
should be reused. If set to
false
, any currently pooled items are destroyed.
另请参阅 Reusing items , TableView::pooled ,和 TableView::reused .
rightColumn : int |
This property holds the rightmost column that is currently visible inside the view.
另请参阅 leftColumn , topRow ,和 bottomRow .
rowHeightProvider : var |
This property can hold a function that returns the row height for each row in the model. It is called whenever
TableView
needs to know the height of a specific row. The function takes one argument,
row
, for which the
TableView
needs to know the height.
Since Qt 5.13, if you want to hide a specific row, you can return
0
height for that row. If you return a negative number,
TableView
calculates the height based on the delegate items.
注意: The rowHeightProvider will usually be called two times when a row is about to load (or when doing layout). First, to know if the row is visible and should be loaded. And second, to determine the height of the row after all items have been loaded. If you need to calculate the row height based on the size of the delegate items, you need to wait for the second call, when all the items have been loaded. You can check for this by calling isRowLoaded (row), and simply return -1 if that is not yet the case.
另请参阅 rowHeightProvider, isRowLoaded (),和 Row heights and column widths .
rowSpacing : real |
This property holds the spacing between the rows.
默认值为
0
.
rows
:
int
|
This property holds the number of rows in the table.
注意: rows is usually equal to the number of rows in the model, but can temporarily differ until all pending model changes have been processed.
This property is read only.
selectionBehavior
:
enumeration
|
This property holds whether the user can select cells, rows or columns.
常量 | 描述 |
---|---|
TableView.SelectionDisabled
|
The user cannot perform selections |
TableView.SelectCells
|
(Default value) The user can select individual cells |
TableView.SelectRows
|
The user can only select rows |
TableView.SelectColumns
|
The user can only select columns |
该特性在 Qt 6.4 引入。
另请参阅 选择项 , selectionMode , selectionModel ,和 keyNavigationEnabled .
selectionMode
:
enumeration
|
若
selectionBehavior
被设为
TableView.SelectCells
, this property holds whether the user can select one cell at a time, or multiple cells. If
selectionBehavior
被设为
TableView.SelectRows
, this property holds whether the user can select one row at a time, or multiple rows. If
selectionBehavior
被设为
TableView.SelectColumns
, this property holds whether the user can select one column at a time, or multiple columns.
The following modes are available:
常量 | 描述 |
---|---|
TableView.SingleSelection
|
The user can select a single cell, row or column. |
TableView.ContiguousSelection
|
The user can select a single contiguous block of cells. An existing selection can be made bigger or smaller by holding down the
Shift
modifier while selecting.
|
TableView.ExtendedSelection
|
(Default value) The user can select multiple individual blocks of cells. An existing selection can be made bigger or smaller by holding down the
Shift
modifier while selecting. A new selection block can be started without clearing the current selection by holding down the
Control
modifier while selecting.
|
该特性在 Qt 6.6 引入。
另请参阅 选择项 , selectionBehavior , selectionModel ,和 keyNavigationEnabled .
selectionModel
:
ItemSelectionModel
|
This property can be set to control which delegate items should be shown as selected, and which item should be shown as current. If the delegate has a
required property bool selected
defined,
TableView
will keep it in sync with the selection state of the corresponding model item in the selection model. If the delegate has a
required property bool current
defined,
TableView
will keep it in sync with selectionModel.currentIndex.
该特性在 Qt 6.2 引入。
另请参阅 选择项 , SelectionRectangle , keyNavigationEnabled ,和 pointerNavigationEnabled .
syncDirection : Qt::Orientations |
若
syncView
被设置在
TableView
, this property controls synchronization of flicking direction(s) for both tables. The default is
Qt.Horizontal | Qt.Vertical
, which means that if you flick either table in either direction, the other table is flicked the same amount in the same direction.
This property and syncView can be used to make two tableViews synchronize with each other smoothly in flicking regardless of the different overshoot/undershoot, velocity, acceleration/deceleration or rebound animation, and so on.
A typical use case is to make several headers flick along with the table.
另请参阅 syncView .
syncView : TableView |
If this property of a TableView is set to another TableView , both the tables will synchronize with regard to flicking, column widths/row heights, and spacing according to syncDirection .
若 syncDirection 包含 Qt.Horizontal , current tableView's column widths, column spacing, and horizontal flicking movement synchronizes with syncView's.
若 syncDirection 包含 Qt.Vertical , current tableView's row heights, row spacing, and vertical flicking movement synchronizes with syncView's.
另请参阅 syncDirection .
topRow : int |
This property holds the topmost row that is currently visible inside the view.
另请参阅 leftColumn , rightColumn ,和 bottomRow .
TableView.editDelegate : 组件 |
This attached property holds the edit delegate. It's instantiated when editing begins, and parented to the delegate it edits. It supports the same required properties as the
TableView delegate
,包括
index
,
row
and
column
. Properties of the model, like
display
and
edit
, are also available (depending on the
role names
exposed by the model).
Editing starts when the actions specified by editTriggers are met, and the current cell is editable.
注意:
In order for a cell to be editable, the model needs to override
QAbstractItemModel::flags
(), and return
Qt::ItemIsEditable
.
You can also open and close the edit delegate manually by calling
edit
() 和
closeEditor
(), respectively. The
Qt::ItemIsEditable
flag will then be ignored.
Editing ends when the user presses
Qt::Key_Enter
or
Qt::Key_Return
(and also
Qt::Key_Tab
or
Qt::Key_Backtab
,若
TableView
has
QQuickItem::activeFocusOnTab
set). In that case, the
TableView::commit
signal will be emitted, so that the edit delegate can respond by writing any modified data back to the model. If editing ends because of other reasons (e.g if the user presses
Qt::Key_Escape
), the signal will not be emitted. In any case will
destruction
() be emitted in the end.
While the edit delegate is showing, the cell underneath will still be visible, and therefore shine through if the edit delegate is translucent, or otherwise doesn't cover the whole cell. If this is not wanted, you can either let the root item of the edit delegate be a solid
Rectangle
, or hide some of the items inside the
TableView delegate.
. The latter can be done by defining a property
required property bool editing
inside it, that you bind to the
visible
property of some of the child items. The following snippet shows how to do that:
delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 required property bool editing Text { id: textField anchors.fill: parent anchors.margins: 5 text: display visible: !editing } TableView.editDelegate: TextField { x: textField.x y: textField.y width: textField.width height: textField.height text: display TableView.onCommit: display = text } }
When the edit delegate is instantiated, TableView 将调用 QQuickItem::forceActiveFocus () on it. If you want active focus to be set on a child of the edit delegate instead, let the edit delegate be a FocusScope .
另请参阅 editTriggers , TableView::commit , edit (), closeEditor (),和 Editing cells .
TableView.view : TableView |
This attached property holds the view that manages the delegate instance. It is attached to each instance of the delegate.
|
This signal is emitted whenever the layout of the loaded rows and columns has potentially changed. This will especially be the case when forceLayout () is called, but also when e.g resizing a row or a column, or when a row or column have entered or left the viewport.
This signal can be used to for example update the geometry of overlays.
注意:
相应处理程序是
onLayoutChanged
.
This signal was introduced in Qt 6.5.
另请参阅 forceLayout () 和 Overlays and underlays .
commit () |
This signal is emitted by the edit delegate
This attached signal is emitted when the edit delegate is active, and the user presses Qt::Key_Enter or Qt::Key_Return . It will also be emitted if TableView has QQuickItem::activeFocusOnTab set, and the user presses Qt::Key_Tab or Qt::Key_Backtab .
This signal will not be emitted if editing ends because of reasons other than the ones mentioned. This includes e.g if the user presses Qt::Key_Escape , taps outside the delegate, the row or column being edited is deleted, or if the application calls closeEditor ().
Upon receiving the signal, the edit delegate should write any modified data back to the model.
注意: This property should be attached to the edit delegate , and not to the delegate .
注意:
相应处理程序是
onCommit
.
另请参阅 TableView::editDelegate , editTriggers ,和 Editing cells .
pooled () |
This signal is emitted after an item has been added to the reuse pool. You can use it to pause ongoing timers or animations inside the item, or free up resources that cannot be reused.
This signal is emitted only if the
reuseItems
特性为
true
.
注意:
相应处理程序是
onPooled
.
另请参阅 Reusing items , reuseItems ,和 reused .
reused () |
This signal is emitted after an item has been reused. At this point, the item has been taken out of the pool and placed inside the content view, and the model properties such as index, row, and column have been updated.
Other properties that are not provided by the model does not change when an item is reused. You should avoid storing any state inside a delegate, but if you do, manually reset that state on receiving this signal.
This signal is emitted when the item is reused, and not the first time the item is created.
This signal is emitted only if the
reuseItems
特性为
true
.
注意:
相应处理程序是
onReused
.
另请参阅 Reusing items , reuseItems ,和 pooled .
|
Returns the cell in the view that maps to modelIndex in the model. Convenience function for doing:
Qt.point(columnAtIndex(modelIndex), rowAtIndex(modelIndex))
A cell is simply a point that combines row and column into a single type.
注意:
that
point.x
will map to the column, and
point.y
will map to the row.
This method was introduced in Qt 6.4.
Returns the cell at the given
position
in the table.
position
should be relative to the
contentItem
. If no
loaded
cell intersects with
position
, the return value will be
point(-1, -1)
.
若
includeSpacing
被设为
true
, a cell's bounding box will be considered to include half the adjacent
rowSpacing
and
columnSpacing
on each side. The default value is
false
.
注意: A Input Handler attached to a TableView installs itself on the contentItem rather than the view. So the position reported by the handler can be used directly in a call to this function without any 映射 .
另请参阅 columnSpacing and rowSpacing .
Convenience for calling
cellAtPosition(Qt.point(x, y), includeSpacing)
.
clearColumnWidths () |
Clears all the column widths set with setColumnWidth ().
注意: 若 syncView is set, together with a Qt.Horizontal syncDirection , the sync view will control the column widths. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
另请参阅 setColumnWidth (), clearRowHeights (),和 Row heights and column widths .
clearRowHeights () |
Clears all the row heights set with setRowHeight ().
注意: 若 syncView is set, together with a Qt.Vertical syncDirection , the sync view will control the row heights. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
另请参阅 setRowHeight (), clearColumnWidths (),和 Row heights and column widths .
|
If the user is editing a cell, calling this function will stop the editing, and destroy the edit delegate instance.
This method was introduced in Qt 6.5.
另请参阅 edit (), TableView::editDelegate ,和 Editing cells .
|
Returns the column in the view that maps to modelIndex in the model.
This method was introduced in Qt 6.4.
另请参阅 rowAtIndex () 和 index ().
返回宽度为给定
column
. If the column is not loaded (and therefore not visible), the return value will be
-1
.
This method was introduced in Qt 6.2.
另请参阅 setColumnWidth (), columnWidthProvider , implicitColumnWidth (), isColumnLoaded (),和 Row heights and column widths .
|
This function starts an editing session for the cell that represents modelIndex . If the user is already editing another cell, that session ends.
Normally you can specify the different ways of starting an edit session by using
editTriggers
instead. If that isn't sufficient, you can use this function. To take full control over cell editing and keep
TableView
from interfering, set
editTriggers
to
TableView.NoEditTriggers
.
注意: The current index 在 selection model will also change to modelIndex .
This method was introduced in Qt 6.5.
另请参阅 closeEditor (), editTriggers , TableView::editDelegate ,和 Editing cells .
qreal explicitColumnWidth ( int column ) |
返回宽度为 column set with setColumnWidth (). This width might differ from the actual width of the column, if a columnWidthProvider is in use. To get the actual width of a column, use columnWidth ().
A return value equal to
0
means that the column has been told to hide. A return value equal to
-1
means that no explicit width has been set for the column.
注意: 若 syncView is set, together with a Qt.Horizontal syncDirection , the sync view will control the column widths. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
另请参阅 setColumnWidth (), columnWidth (),和 Row heights and column widths .
qreal explicitRowHeight ( int row ) |
Returns the height of the row set with setRowHeight (). This height might differ from the actual height of the column, if a rowHeightProvider is in use. To get the actual height of a row, use rowHeight ().
A return value equal to
0
means that the row has been told to hide. A return value equal to
-1
means that no explicit height has been set for the row.
注意: 若 syncView is set, together with a Qt.Vertical syncDirection , the sync view will control the row heights. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
另请参阅 setRowHeight (), rowHeight (),和 Row heights and column widths .
forceLayout () |
Responding to changes in the model are batched so that they are handled only once per frame. This means the TableView delays showing any changes while a script is being run. The same is also true when changing properties, such as rowSpacing or leftMargin .
This method forces the TableView to immediately update the layout so that any recent changes take effect.
Calling this function re-evaluates the size and position of each visible row and column. This is needed if the functions assigned to rowHeightProvider or columnWidthProvider return different values than what is already assigned.
Returns the implicit width of the given
column
. If the column is not loaded (and therefore not visible), the return value will be
-1
.
The implicit width of a column is the largest implicitWidth found among the currently loaded delegate items inside that column. Widths returned by the columnWidthProvider will not be taken into account.
This method was introduced in Qt 6.2.
另请参阅 columnWidthProvider , columnWidth (), isColumnLoaded (),和 Row heights and column widths .
Returns the implicit height of the given
row
. If the row is not loaded (and therefore not visible), the return value will be
-1
.
The implicit height of a row is the largest implicitHeight found among the currently loaded delegate items inside that row. Heights returned by the rowHeightProvider will not be taken into account.
This method was introduced in Qt 6.2.
另请参阅 rowHeightProvider , rowHeight (), isRowLoaded (),和 Row heights and column widths .
返回 QModelIndex that maps to row and column in the view.
row
and
column
should be the row and column in the view (table row and table column), and not a row and column in the model. For a plain
TableView
, this is equivalent of calling
model.index(row, column).
But for a subclass of
TableView
, like
TreeView
, where the data model is wrapped inside an internal proxy model that flattens the tree structure into a table, you need to use this function to resolve the model index.
This method was introduced in Qt 6.4.3.
另请参阅 rowAtIndex () 和 columnAtIndex ().
返回
true
若给定
column
is loaded.
A column is loaded when TableView has loaded the delegate items needed to show the column inside the view. This also usually means that the column is visible for the user, but not always.
This function can be used whenever you need to iterate over the delegate items for a column, e.g from a columnWidthProvider , to be sure that the delegate items are available for iteration.
This method was introduced in Qt 6.2.
返回
true
若给定
row
is loaded.
A row is loaded when TableView has loaded the delegate items needed to show the row inside the view. This also usually means that the row is visible for the user, but not always.
This function can be used whenever you need to iterate over the delegate items for a row, e.g from a rowHeightProvider , to be sure that the delegate items are available for iteration.
This method was introduced in Qt 6.2.
Returns the delegate item at
cell
if loaded, otherwise
null
.
注意: only the items that are visible in the view are normally loaded. As soon as a cell is flicked out of the view, the item inside will either be unloaded or placed in the recycle pool. As such, the return value should never be stored.
|
Returns the instantiated delegate item for the cell that represents
index
. If the item is not
loaded
, the value will be
null
.
注意: only the items that are visible in the view are normally loaded. As soon as a cell is flicked out of the view, the item inside will either be unloaded or placed in the recycle pool. As such, the return value should never be stored.
注意:
若
model
is not a
QAbstractItemModel
,还可以使用
itemAtCell(Qt.point
(column, row)). But be aware that
point.x
maps to columns and
point.y
maps to rows.
This method was introduced in Qt 6.5.
|
Convenience function for doing:
modelIndex(cell.y, cell.x)
A cell is simply a point that combines row and column into a single type.
注意:
point.x
will map to the column, and
point.y
will map to the row.
This method was introduced in Qt 6.4.
positionViewAtCell ( point cell , PositionMode mode , point offset , rect subRect ) |
Positions contentX and contentY such that cell is at the position specified by mode . mode can be an or-ed combination of the following:
常量 | 描述 |
---|---|
TableView.AlignLeft
|
Position the cell at the left of the view. |
TableView.AlignHCenter
|
Position the cell at the horizontal center of the view. |
TableView.AlignRight
|
Position the cell at the right of the view. |
TableView.AlignTop
|
Position the cell at the top of the view. |
TableView.AlignVCenter
|
Position the cell at the vertical center of the view. |
TableView.AlignBottom
|
Position the cell at the bottom of the view. |
TableView.AlignCenter
|
The same as ( TableView .AlignHCenter | TableView .AlignVCenter) |
TableView.Visible
|
If any part of the cell is visible then take no action. Otherwise move the content item so that the entire cell becomes visible. |
TableView.Contain
|
If the entire cell is visible then take no action. Otherwise move the content item so that the entire cell becomes visible. If the cell is bigger than the view, the top-left part of the cell will be preferred. |
If no vertical alignment is specified, vertical positioning will be ignored. The same is true for horizontal alignment.
Optionally, you can specify offset to move contentX and contentY an extra number of pixels beyond the target alignment. E.g if you want to position the view so that cell [10, 10] ends up at the top-left corner with a 5px margin, you could do:
positionViewAtCell(Qt.point(10, 10), TableView.AlignLeft | TableView.AlignTop, Qt.point(-5, -5))
As of Qt 6.4, you can specify a subRect to position on a rectangle inside the cell , rather than on the bounding rectangle of the whole cell. This can be useful if the cell is e.g larger than the view, and you want to ensure that a specific part of it is visible. The subRect needs to be valid to be taken into consideration.
注意: It is not recommended to use contentX or contentY to position the view at a particular cell. This is unreliable since removing items from the start of the table does not cause all other items to be repositioned. TableView can also sometimes place rows and columns at approximate positions to optimize for speed. The only exception is if the cell is already visible in the view, which can be checked upfront by calling itemAtCell ().
Methods should only be called after the Component has completed. To position the view at startup, this method should be called by Component.onCompleted. For example, to position the view at the end:
Component.onCompleted: positionViewAtCell(Qt.point(columns - 1, rows - 1), TableView.AlignRight | TableView.AlignBottom)
注意: The second argument to this function used to be Qt.Alignment. For backwards compatibility, that enum can still be used. The change to use PositionMode was done in Qt 6.4.
另请参阅 animate .
positionViewAtColumn ( int column , PositionMode mode , real offset , rect subRect ) |
Positions {Flickable::}{contentX} such that column is at the position specified by mode , offset and subRect .
Convenience method for calling
positionViewAtCell(Qt.point(column, 0), mode & Qt.AlignHorizontal_Mask, offset, subRect)
|
Positions the view such that index is at the position specified by mode , offset and subRect .
Convenience method for calling
positionViewAtRow(rowAtIndex(index), mode & Qt.AlignVertical_Mask, offset.y, subRect) positionViewAtColumn(columnAtIndex(index), mode & Qt.AlignVertical_Mask, offset.x, subRect)
This method was introduced in Qt 6.5.
positionViewAtRow ( int row , PositionMode mode , real offset , rect subRect ) |
Positions {Flickable::}{contentY} such that row is at the position specified by mode , offset and subRect .
Convenience method for calling
positionViewAtCell(Qt.point(0, row), mode & Qt.AlignVertical_Mask, offset, subRect)
|
Returns the row in the view that maps to modelIndex in the model.
This method was introduced in Qt 6.4.
另请参阅 columnAtIndex () 和 index ().
返回高度为给定
row
. If the row is not loaded (and therefore not visible), the return value will be
-1
.
This method was introduced in Qt 6.2.
另请参阅 setRowHeight (), rowHeightProvider , implicitRowHeight (), isRowLoaded (),和 Row heights and column widths .
Sets the explicit column width of column column to size .
If you want to read back the values you set with this function, you should use explicitColumnWidth (). columnWidth () will return the actual size of the column, which can be different if a columnWidthProvider 有设置。
当 TableView needs to resolve the width of column , it will first try to call the columnWidthProvider . Only if a provider is not set, will the widths set with this function be used by default. You can, however, call explicitColumnWidth () from within the provider, and if needed, moderate the values to e.g always be within a certain interval. The following snippet shows an example on how to do that:
columnWidthProvider: function(column) { let w = explicitColumnWidth(column) if (w >= 0) return Math.max(100, w); return implicitColumnWidth(column) }
若
size
等于
0
, the column will be hidden. If
size
等于
-1
, the column will be reset back to use
implicitColumnWidth
(). You are allowed to specify column sizes for columns that are outside the size of the model.
注意: The sizes you set will not be cleared if you change the model . To clear the sizes, you need to call clearColumnWidths () explicitly.
注意: 若 syncView is set, together with a Qt.Horizontal syncDirection , the sync view will control the column widths. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
注意:
For models with
lots
of columns, using setColumnWidth() to set the widths for all the columns at start-up, can be suboptimal. This will consume start-up time and memory (for storing all the widths). A more scalable approach is to use a
columnWidthProvider
instead, or rely on the implicit width of the delegate. A
columnWidthProvider
will only be called on an as-needed basis, and will not be affected by the size of the model.
另请参阅 columnWidth (), explicitColumnWidth (), setRowHeight (), clearColumnWidths (),和 Row heights and column widths .
Sets the explicit row height of row row to size .
If you want to read back the values you set with this function, you should use explicitRowHeight (). rowHeight () will return the actual height of the row, which can be different if a rowHeightProvider 有设置。
当 TableView needs to resolve the height of row , it will first try to call the rowHeightProvider . Only if a provider is not set, will the heights set with this function be used by default. You can, however, call explicitRowHeight () from within the provider, and if needed, moderate the values to e.g always be within a certain interval. The following snippet shows an example on how to do that:
rowHeightProvider: function(row) { let h = explicitRowHeight(row) if (h >= 0) return Math.max(100, h); return implicitRowHeight(row) }
若
size
等于
0
, the row will be hidden. If
size
等于
-1
, the row will be reset back to use
implicitRowHeight
(). You are allowed to specify row sizes for rows that are outside the size of the model.
注意: The sizes you set will not be cleared if you change the model . To clear the sizes, you need to call clearRowHeights () explicitly.
注意: 若 syncView is set, together with a Qt.Vertical syncDirection , the sync view will control the row heights. Therefore, in that case, any call to this function will be forwarded to the sync view instead.
注意:
For models with
lots
of rows, using setRowHeight() to set the heights for all the rows at start-up, can be suboptimal. This will consume start-up time and memory (for storing all the heights). A more scalable approach is to use a
rowHeightProvider
instead, or rely on the implicit height of the delegate. A
rowHeightProvider
will only be called on an as-needed basis, and will not be affected by the size of the model.
另请参阅 rowHeight (), explicitRowHeight (), setColumnWidth (),和 Row heights and column widths .