The QTable class provides a flexible editable table widget.
QTable is easy to use, although it does have a large API because
of the comprehensive functionality that it provides. QTable
includes functions for manipulating headers, rows and columns,
cells and selections. QTable also provides in-place editing and
drag and drop, as well as a useful set of
signals. QTable efficiently supports very
large tables, for example, tables one million by one million cells
are perfectly possible. QTable is economical with memory, using
none for unused cells.
QTable *table = new QTable( 100, 250, this );
table->setPixmap( 3, 2, pix );
table->setText( 3, 2, "A pixmap" );
The first line constructs the table specifying its size in rows
and columns. We then insert a pixmap and some text into the samecell, with the pixmap appearing to the
left of the text. QTable cells can be populated with
QTableItems, QComboTableItems or by QCheckTableItems.
By default a vertical header appears at the left of the table
showing row numbers and a horizontal header appears at the top of
the table showing column numbers. (The numbers displayed start at
1, although row and column numbers within QTable begin at 0.)
QTable supports a header column, e.g. to display row numbers, and
a header row, e.g to display column titles. To set row or column
labels use QHeader::setLabel() on the pointers returned by
verticalHeader() and horizontalHeader() respectively. The vertical
header is displayed within the table's left margin whose width is
set with setLeftMargin(). The horizontal header is displayed
within the table's top margin whose height is set with
setTopMargin(). The table's grid can be switched off with
setShowGrid(). If you want to hide a horizontal header call
hide(), and call setTopMargin( 0 ) so that the area the header
would have occupied is reduced to zero size.
Header labels are indexed via their section numbers. Note that the
default behavior of QHeader regarding section numbers is overriden
for QTable. See the explanation below in the Rows and Columns
section in the discussion of moving columns and rows.
Rows and Columns
Row and column sizes are set with setRowHeight() and
setColumnWidth(). If you want a row high enough to show the
tallest item in its entirety, use adjustRow(). Similarly, to make
a column wide enough to show the widest item use adjustColumn().
If you want the row height and column width to adjust
automatically as the height and width of the table changes use
setRowStretchable() and setColumnStretchable().
Rows and columns can be set to be moveable, i.e. the user can drag
them to reorder them, using rowMovingEnabled() and
columnMovingEnabled(). For performance reasons, the default
behavior of QHeader section numbers is overridden by QTable.
Currently in QTable, when a row or column is dragged and
reordered, the section number is also changed to its new position.
Therefore, there is no difference between the section and the
index fields in QHeader. The QTable QHeader classes do not provide
a mechanism for indexing independently of the user interface
ordering.
The table can be sorted using sortColumn(). Users can sort a
column by clicking its header if setSorting() is set to TRUE. Rows
can be swapped with swapRows(), columns with swapColumns() and
cells with swapCells().
For editable tables (see setReadOnly()) you can set the read-only
property of individual rows and columns with setRowReadOnly() and
setColumnReadOnly(). (Whether a cell is editable or read-only
depends on these settings and the cell's QTableItem::EditType.)
The row and column which have the focus are returned by
currentRow() and currentColumn() respectively.
Although many QTable functions operate in terms of rows and
columns the indexOf() function returns a single integer
identifying a particular cell.
Cells
All of a QTable's cells are empty when the table is constructed.
There are two approaches to populating the table's cells. The
first and simplest approach is to use QTableItems or QTableItem
subclasses. The second approach doesn't use QTableItems at all
which is useful for very large sparse tables but requires you to
reimplement a number of functions. We'll look at each approach in
turn.
To put a string in a cell use setText(). This function will create
a new QTableItem for the cell if one doesn't already exist, and
displays the text in it. By default the table item's widget will
be a QLineEdit. A pixmap may be put in a cell with setPixmap(),
which also creates a table item if required. A cell may contain both a pixmap and text; the pixmap is displayed to the left of the
text. Another approach is to construct a QTableItem or QTableItem
subclass, set its properties, then insert it into a cell with
setItem().
If you want cells which contain comboboxes use the QComboTableItem
class. Similarly if you require cells containing checkboxes use
the QCheckTableItem class. These table items look and behave just
like the combobox or checkbox widgets but consume far less memory.
for ( int j = 0; j < numRows; ++j )
table.setItem( j, 1, new QCheckTableItem( &table, "Check me" ) );
In the example above we create a column of QCheckTableItems and
insert them into the table using setItem().
QTable takes ownership of its QTableItems and will delete them
when the table itself is destroyed. You can take ownership of a
table item using takeItem() which you use to move a cell's
contents from one cell to another, either within the same table,
or from one table to another. (See also, swapCells()).
In-place editing of the text in QTableItems, and the values in
QComboTableItems and QCheckTableItems works automatically. Cells
may be editable or read-only, see QTableItem::EditType. If you
want fine control over editing see beginEdit() and endEdit().
The contents of a cell can be retrieved as a QTableItem using
item(), or as a string with text() or as a pixmap (if there is
one) with pixmap(). A cell's bounding rectangle is given by
cellGeometry(). Use updateCell() to repaint a cell, for example to
clear away a cell's visual representation after it has been
deleted with clearCell(). The table can be forced to scroll to
show a particular cell with ensureCellVisible(). The isSelected()
function indicates if a cell is selected.
It is possible to use your own widget as a cell's widget using
setCellWidget(), but subclassing QTableItem might be a simpler
approach. The cell's widget (if there is one) can be removed with
clearCellWidget().
Large tables
For large, sparse, tables using QTableItems or other widgets is
inefficient. The solution is to draw the cell as it should
appear and to create and destroy cell editors on demand.
This approach requires that you reimplement various functions.
Reimplement paintCell() to display your data, and createEditor()
and setCellContentFromEditor() to facilitate in-place editing. It
is very important to reimplement resizeData() to have no
functionality, to prevent QTable from attempting to create a huge
array. You will also need to reimplement item(), setItem(),
clearCell(), and insertWidget(), cellWidget() and
clearCellWidget(). In almost every circumstance (for sorting,
removing and inserting columns and rows, etc.,) you must also
reimplement swapRows(), swapCells() and swapColumns(), including
header handling.
If you represent active cells with a dictionary of QTableItems and
QWidgets, i.e. only store references to cells that are actually
used, many of the functions can be implemented with a single line
of code. (See the table/bigtable/main.cpp example.)
For more information on cells see the QTableItem documenation.
Selections
QTable's support single selection, multi-selection (multiple
cells) or no selection. The selection mode is set with
setSelectionMode(). Use isSelected() to determine if a particular
cell is selected, and isRowSelected() and isColumnSelected() to
see if a row or column is selected.
QTable's support multiple selections. You can programmatically
select cells with addSelection(). The number of selections is
given by numSelections(). The current selection is returned by
currentSelection(). You can remove a selection with
removeSelection() and remove all selections with clearSelection().
Selections are QTableSelection objects.
Signals
When the user clicks a cell the currentChanged() signal is
emitted. You can also connect to the lower level clicked(),
doubleClicked() and pressed() signals. If the user changes the
selection the selectionChanged() signal is emitted; similarly if
the user changes a cell's value the valueChanged() signal is
emitted. If the user right-clicks (or presses the appropriate
platform-specific key sequence) the contextMenuRequested() signal
is emitted. If the user drops a drag and drop object the dropped()
signal is emitted with the drop event.
QTable::NotEditing - No cell is currently being edited.
QTable::Editing - A cell is currently being edited. The editor was
initialised with the cell's contents.
QTable::Replacing - A cell is currently being edited. The editor was
not initialised with the cell's contents.
QTable::FocusStyle
Specifies how the current cell (focus cell) is drawn.
QTable::FollowStyle - The current cell is drawn according to the
current style and the cell's background is also drawn selected, if
the current cell is within a selection
QTable::SpreadSheet - The current cell is drawn as in a spreadsheet.
This means, it is signified by a black rectangle around the cell,
and the background of the current cell is always drawn with the
widget's base color - even when selected.
QTable::SelectionMode
QTable::NoSelection - No cell can be selected by the user.
QTable::Single - The user may only select a single range of cells.
QTable::Multi - The user may select multiple ranges of cells.
QTable::SingleRow - The user may select one row at once (the current
item's row is always selected).
QTable::MultiRow - The user may select multiple rows.
This function is called to activate the next cell if in-place
editing was finished by pressing the Enter key.
The default behaviour is to move from top to bottom, i.e. move to
the cell beneath the cell being edited. Reimplement this function
if you want different behaviour, e.g. moving from left to right.
int QTable::addSelection ( const QTableSelection & s ) [virtual]
Adds a selection described by s to the table and returns its
number or -1 if the selection is invalid.
QWidget * QTable::beginEdit ( int row, int col, bool replace ) [virtual protected]
This function is called to start in-place editing of the cell at
row, col. Editing is achieved by creating an editor
(createEditor() is called) and setting the cell's editor with
setCellWidget() to the newly created editor. (After editing is
complete endEdit() will be called to replace the cell's content
with the editor's content.) If replace is TRUE the editor will
be initialized with the cell's content (if any), i.e. the user
will be modifying the original cell content; otherwise the user
will be entering new data.
QRectQTable::cellGeometry ( int row, int col ) const [virtual]
Returns the bounding rectangle of the cell at row, col in
content coordinates.
QRectQTable::cellRect ( int row, int col ) const [virtual]
Returns the geometry of cell row, col in the cell's
coordinate system. This is a convenience function useful in
paintCell(). It is equivalent to QRect( QPoint(0,0), cellGeometry(
row, col).size() );
This function deletes the widget at row, col. Note that the
widget is not deleted immediately; instead QObject::deleteLater()
is called on the widget to avoid problems with timing issues.
void QTable::clicked ( int row, int col, int button, const QPoint & mousePos ) [signal]
This signal is emitted when mouse button button is clicked. The
cell where the event took place is at row, col, and the
mouse's position is in mousePos.
void QTable::columnWidthChanged ( int col ) [virtual protected slot]
This function should be called whenever the column width of col
has been changed. It updates the geometry of any affected columns
and repaints the table to reflect the changes it has made.
void QTable::contentsDragEnterEvent ( QDragEnterEvent * e ) [virtual protected]
This event handler is called whenever a QTable object receives a
QDragEnterEvente, i.e. when the user pressed the mouse
button to drag something.
The focus is moved to the cell where the QDragEnterEvent occurred.
void QTable::contextMenuRequested ( int row, int col, const QPoint & pos ) [signal]
This signal is emitted when the user invokes a context menu with
the right mouse button (or with a system-specific keypress). The
cell where the event took place is at row, col. pos is
the position where the context menu will appear in the global
coordinate system.
QWidget * QTable::createEditor ( int row, int col, bool initFromCell ) const [virtual protected]
This function returns the widget which should be used as an editor
for the contents of the cell at row, col.
If initFromCell is TRUE, the editor is used to edit the current
contents of the cell (so the editor widget should be initialized
with this content). If initFromCell is FALSE, the content of
the cell is replaced with the new content which the user entered
into the widget created by this function.
The default functionality is as follows: if initFromCell is
TRUE or the cell has a QTableItem and the table item's
QTableItem::isReplaceable() is FALSE then the cell is asked to
create an appropriate editor (using QTableItem::createEditor()).
Otherwise a QLineEdit is used as the editor.
If you want to create your own editor for certain cells, implement
a custom QTableItem subclass and reimplement
QTableItem::createEditor().
If you are not using QTableItems and you don't want to use a
QLineEdit as the default editor, subclass QTable and reimplement
this function with code like this:
QTableItem *i = item( row, col );
if ( initFromCell || ( i && !i->isReplaceable() ) )
// If we had a QTableItem ask the base class to create the editor
return QTable::createEditor( row, col, initFromCell );
else
return ...(create your own editor)
Ownership of the editor widget is transferred to the caller.
If you reimplement this function return 0 for read-only cells. You
will need to reimplement setCellContentFromEditor() to retrieve
the data the user entered.
void QTable::doubleClicked ( int row, int col, int button, const QPoint & mousePos ) [signal]
This signal is emitted when mouse button button is
double-clicked. The cell where the event took place is at row,
col, and the mouse's position is in mousePos.
bool QTable::dragEnabled () const [slot]
If this function returns TRUE, the table supports dragging.
If the user presses the mouse on a selected cell, starts moving
(i.e. dragging), and dragEnabled() is TRUE, this function is
called to obtain a drag object. A drag using this object begins
immediately unless dragObject() returns 0.
By default this function returns 0. You might reimplement it and
create a QDragObject depending on the selected items.
void QTable::drawContents ( QPainter * p, int cx, int cy, int cw, int ch ) [virtual protected]
Draws the table contents on the painter p. This function is
optimized so that it only draws the cells inside the cw pixels
wide and ch pixels high clipping rectangle at position cx,
cy.
Additionally, drawContents() highlights the current cell.
This signal is emitted when a drop event occurred on the table.
e contains information about the drop.
void QTable::editCell ( int row, int col, bool replace = FALSE ) [virtual slot]
Starts editing the cell at row, col.
If replace is TRUE the content of this cell will be replaced by
the content of the editor when editing is finished, i.e. the user
will be entering new data; otherwise the current content of the
cell (if any) will be modified in the editor.
void QTable::endEdit ( int row, int col, bool accept, bool replace ) [virtual protected]
This function is called when in-place editing of the cell at row, col is requested to stop.
If the cell is not being edited or accept is FALSE the function
returns and the cell's contents are left unchanged.
If accept is TRUE the content of the editor must be transferred
to the relevant cell. If replace is TRUE the current content of
this cell should be replaced by the content of the editor (this
means removing the current QTableItem of the cell and creating a
new one for the cell). Otherwise (if possible) the content of the
editor should just be set to the existing QTableItem of this cell.
bool QTable::isColumnSelected ( int col, bool full = FALSE ) const
Returns TRUE if column col is selected; otherwise returns FALSE.
If full is FALSE (the default), 'column is selected' means that
at least one cell in the column is selected. If full is TRUE,
then 'column is selected' means every cell in the column is
selected.
bool QTable::isRowSelected ( int row, bool full = FALSE ) const
Returns TRUE if row row is selected; otherwise returns FALSE.
If full is FALSE (the default), 'row is selected' means that at
least one cell in the row is selected. If full is TRUE, then 'row
is selected' means every cell in the row is selected.
Paints the cell at row, col on the painter p. The painter
has already been translated to the cell's origin. cr describes
the cell coordinates in the content coordinate system.
If selected is TRUE the cell is highlighted.
cg is the colorgroup which should be used to draw the cell
content.
If you want to draw custom cell content, for example right-aligned
text, you must either reimplement paintCell(), or subclass
QTableItem and reimplement QTableItem::paint() to do the custom
drawing.
If you're using a QTableItem subclass, for example, to store a
data structure, then reimplementing QTableItem::paint() may be the
best approach. For data you want to draw immediately, e.g. data
retrieved from a database, it is probably best to reimplement
paintCell(). Note that if you reimplement paintCell(), i.e. don't
use QTableItems, you must reimplement other functions: see the
notes on large tables.
Note that the painter is not clipped by default in order to get
maximum efficiency. If you want clipping, use code like this:
void QTable::pressed ( int row, int col, int button, const QPoint & mousePos ) [signal]
This signal is emitted when mouse button button is pressed. The
cell where the event took place is at row, col, and the
mouse's position is in mousePos.
void QTable::removeColumn ( int col ) [virtual slot]
Removes column col, and deletes all its cells including any
table items and widgets the cells may contain. Also clears the
selection(s).
Removes the columns listed in the array cols, and deletes all
their cells including any table items and widgets the cells may
contain.
The array passed in must only contain valid columns (in the range
from 0 to numCols() - 1) with no duplicates, and must be sorted in
ascending order. Also clears the selection(s).
Removes the rows listed in the array rows, and deletes all their
cells including any table items and widgets the cells may contain.
The array passed in must only contain valid rows (in the range
from 0 to numRows() - 1) with no duplicates, and must be sorted in
ascending order. Also clears the selection(s).
void QTable::resizeData ( int len ) [virtual protected]
This is called when QTable's internal array needs to be resized to
len elements.
If you don't use QTableItems you should reimplement this as an
empty method to avoid wasting memory. See the notes on large tables for further details.
int QTable::rowAt ( int y ) const [virtual]
Returns the number of the row at position y. y must be given
in content coordinates.
void QTable::rowHeightChanged ( int row ) [virtual protected slot]
This function should be called whenever the row height of row
has been changed. It updates the geometry of any affected rows and
repaints the table to reflect the changes it has made.
void QTable::rowIndexChanged ( int section, int fromIndex, int toIndex ) [virtual protected slot]
This function is called when the order of the rows is to be
changed, i.e. the user moved the row header section section
from fromIndex to toIndex.
If you want to change the order programmatically, call swapRows()
or swapColumns();
Returns the current selection mode.
See the "selectionMode" property for details.
void QTable::setCellContentFromEditor ( int row, int col ) [virtual protected]
This function is called to replace the contents of the cell at row, col with the contents of the cell's editor. If a
QTableItem already exists for this cell, it is removed first (see
clearCell()).
If for example, you want to create different QTableItems
depending on the contents of the editor, you might reimplement
this function.
If you want to work without QTableItems, you will need to
reimplement this function to save the data the user entered into
your data structure. (See the notes on large tables.)
void QTable::setCellWidget ( int row, int col, QWidget * e ) [virtual]
Sets the widget e to the cell at row, col and takes care of
placing and resizing the widget when the cell geometry changes.
By default widgets are inserted into a vector with numRows() *
numCols() elements. In very large tables you will probably want to
store the widgets in a data structure that consumes less memory (see
the notes on large tables). To support the use of your own data
structure this function calls insertWidget() to add the widget to
the internal data structure. To use your own data structure
reimplement insertWidget(), cellWidget() and clearCellWidget().
Cell widgets are created dynamically with the new operator. The
cell widgets are destroyed automatically once the table is
destroyed; the table takes ownership of the widget when using
setCellWidget.
void QTable::setColumnStretchable ( int col, bool stretch ) [virtual slot]
If stretch is TRUE, column col is set to be stretchable;
otherwise column col is set to be unstretchable.
If the table widget's width decreases or increases stretchable
columns will grow narrower or wider to fit the space available as
completely as possible. The user cannot manually resize stretchable
columns.
Sets how the current (focus) cell is drawn to fs.
See the "focusStyle" property for details.
void QTable::setItem ( int row, int col, QTableItem * item ) [virtual]
Inserts the table item item into the table at row row,
column col, and repaints the cell. If a table item already
exists in this cell it is deleted and replaced with item. The
table takes ownership of the table item.
Sets the number of columns in the table to r.
See the "numCols" property for details.
void QTable::setNumRows ( int r ) [virtual slot]
Sets the number of rows in the table to r.
See the "numRows" property for details.
void QTable::setPixmap ( int row, int col, const QPixmap & pix ) [virtual]
Sets the pixmap in the cell at row, col to pix.
If the cell does not contain a table item a QTableItem is created
with an EditType of OnTyping,
otherwise the existing table item's pixmap (if any) is replaced
with pix.
void QTable::setRowStretchable ( int row, bool stretch ) [virtual slot]
If stretch is TRUE, row row is set to be stretchable;
otherwise row row is set to be unstretchable.
If the table widget's height decreases or increases stretchable
rows will grow shorter or taller to fit the space available as
completely as possible. The user cannot manually resize
stretchable rows.
Sets the current selection mode to mode.
See the "selectionMode" property for details.
void QTable::setShowGrid ( bool b ) [virtual slot]
Sets whether the table's grid is displayed to b.
See the "showGrid" property for details.
void QTable::setSorting ( bool b ) [virtual slot]
Sets whether a click on the header of a column sorts that column to b.
See the "sorting" property for details.
void QTable::setText ( int row, int col, const QString & text ) [virtual]
Sets the text in the cell at row, col to text.
If the cell does not contain a table item a QTableItem is created
with an EditType of OnTyping,
otherwise the existing table item's text (if any) is replaced with
text.
void QTable::swapCells ( int row1, int col1, int row2, int col2 ) [virtual slot]
Swaps the contents of the cell at row1, col1 with the
contents of the cell at row2, col2.
This function is also called when the table is sorted.
If you don't use QTableItems and want your users to be able to
swap cells, you will need to reimplement this function. (See the
notes on large tables.)
void QTable::swapColumns ( int col1, int col2, bool swapHeader = FALSE ) [virtual slot]
Swaps the data in col1 with col2.
This function is used to swap the positions of two columns. It is
called when the user changes the order of columns (see
setColumnMovingEnabled(), and when columns are sorted.
If you don't use QTableItems and want your users to be able to
swap columns you will need to reimplement this function. (See the
notes on large tables.)
If swapHeader is TRUE, the columns' header contents is also
swapped.
void QTable::swapRows ( int row1, int row2, bool swapHeader = FALSE ) [virtual slot]
Swaps the data in row1 and row2.
This function is used to swap the positions of two rows. It is
called when the user changes the order of rows (see
setRowMovingEnabled()), and when rows are sorted.
If you don't use QTableItems and want your users to be able to
swap rows, e.g. for sorting, you will need to reimplement this
function. (See the notes on large tables.)
If swapHeader is TRUE, the rows' header contents is also
swapped.
void QTable::takeItem ( QTableItem * i ) [virtual]
Takes the table item i out of the table. This function does not delete the table item. You must either delete the table item
yourself or put it into a table (using setItem()) which will then
take ownership of it.
Use this function if you want to move an item from one cell in a
table to another, or to move an item from one table to another,
reinserting the item with setItem().
If you want to exchange two cells use swapCells().
QStringQTable::text ( int row, int col ) const [virtual]
Returns the text in the cell at row, col, or QString::null
if the relevant item does not exist or has no text.
Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter
ou par MP !