Qt Class之QTableWidget

来源:互联网 发布:c递归算法经典实例 编辑:程序博客网 时间:2024/05/21 07:09

Qt ClassQTableWidget

文档名称

Qt ClassQTableWidget

创建时间

2012-9-7

修改时间

2012-9-7

创建人

Baifx

简介(收获)

QTableWidgetQTableWidgetItemQTableView

一、综述。

1、继承关系。

QTableWidget类:

QHeaderView类:


2、官方描述。

QTableWidget

The QTableWidget class provides an item-based table view with a default model.

Table widgets provide standard table display facilities for applications. The items in a QTableWidget are provided byQTableWidgetItem.

If you want a table that uses your own data model you should useQTableView rather than this class.

Table widgets can be constructed with the required numbers of rows and columns:

    tableWidget = new QTableWidget(12, 3, this);

Alternatively, tables can be constructed without a given size and resized later:

     tableWidget = new QTableWidget(this);

     tableWidget->setRowCount(10);

     tableWidget->setColumnCount(5);

Items are created ouside the table (with no parent widget) and inserted into the table withsetItem():

     QTableWidgetItem *newItem = newQTableWidgetItem(tr("%1").arg(

         (row+1)*(column+1)));

     tableWidget->setItem(row, column, newItem);

If you want to enable sorting in your table widget, do so after you have populated it with items, otherwise sorting may interfere with the insertion order (seesetItem() for details).

Tables can be given both horizontal and vertical headers. The simplest way to create the headers is to supply a list of strings to thesetHorizontalHeaderLabels() andsetVerticalHeaderLabels() functions. These will provide simple textual headers for the table's columns and rows. More sophisticated headers can be created from existing table items that are usually constructed outside the table. For example, we can construct a table item with an icon and aligned text, and use it as the header for a particular column:

QTableWidgetItem *cubesHeaderItem = newQTableWidgetItem(tr("Cubes"));

     cubesHeaderItem->setIcon(QIcon(QPixmap(":/Images/cubed.png")));

     cubesHeaderItem->setTextAlignment(Qt::AlignVCenter);

The number of rows in the table can be found withrowCount(), and the number of columns withcolumnCount(). The table can be cleared with theclear() function.

QTableWidgetItem

The QTableWidgetItem class provides an item for use with theQTableWidget class.

Table items are used to hold pieces of information for table widgets.Items usually contain text, icons, or checkboxes

The QTableWidgetItem class is a convenience class that replaces the QTableItem class in Qt 3.It provides an item for use with the QTableWidget class.

Top-level items are constructed without a parent then inserted at the position specified by a pair of row and column numbers:

     QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1").arg(

         pow(row, column+1)));

     tableWidget->setItem(row, column, newItem);

Each item can have its own background brush which is set with thesetBackground() function. The current background brush can be found withbackground(). The text label for each item can be rendered with its own font and brush. These are specified with the setFont() andsetForeground() functions, and read withfont() andforeground().

By default, items are enabled, editable, selectable, checkable, and can be used both as the source of a drag and drop operation and as a drop target.Each item's flags can be changed by calling setFlags() with the appropriate value (seeQt::ItemFlags). Checkable items can be checked and unchecked with thesetCheckState() function. The correspondingcheckState() function indicates whether the item is currently checked.

Subclassing

When subclassing QTableWidgetItem to provide custom items, it is possible to define new types for them so that they can be distinguished from standard items. The constructors for subclasses that require this feature need to call the base class constructor with a new type value equal to or greater thanUserType.

QHeaderView

The QHeaderView class provides a header row or header column for item views.

A QHeaderView displays the headers used in item views such as theQTableView andQTreeView classes.It takes the place of Qt3's QHeader class previously used for the same purpose, but uses the Qt's model/view architecture for consistency with the item view classes.

The QHeaderView class is one of theModel/View Classes and is part of Qt'smodel/view framework.

The header gets the data for each section from the model using theQAbstractItemModel::headerData() function. You can set the data by usingQAbstractItemModel::setHeaderData().

Each header has an orientation() and a number of sections, given by thecount() function. A section refers to a part of the header - either a row or a column, depending on the orientation.

Sections can be moved and resized using moveSection() andresizeSection(); they can also be hidden and shown withhideSection() andshowSection().

Each section of a header is described by a section ID, specified by its section(), and can be located at a particularvisualIndex() in the header. A section can have a sort indicator set withsetSortIndicator(); this indicates whether the items in the associated item view will be sorted in the order given by the section.

For a horizontal header the section is equivalent to a column in the model, and for a vertical header the section is equivalent to a row in the model.

Moving Header Sections

A header can be fixed in place, or made movable withsetMovable(). It can be made clickable withsetClickable(), and has resizing behavior in accordance withsetResizeMode().

Note: Double-clicking on a header to resize a section only applies for visible rows.

A header will emit sectionMoved() if the user moves a section,sectionResized() if the user resizes a section, andsectionClicked() as well assectionHandleDoubleClicked() in response to mouse clicks. A header will also emit sectionCountChanged() andsectionAutoResize().

You can identify a section using the logicalIndex() andlogicalIndexAt() functions, or by its index position, using thevisualIndex() andvisualIndexAt() functions. The visual index will change if a section is moved, but the logical index will not change.

Appearance

QTableWidget andQTableView create default headers. If you want the headers to be visible, you can usesetVisible().

Not all ItemDataRoles will have an effect on a QHeaderView. If you need to draw other roles, you can subclass QHeaderView and reimplement paintEvent(). QHeaderView respects the following item data roles: TextAlignmentRole,

DisplayRole,FontRole,DecorationRole,ForegroundRole, andBackgroundRole.

Note: Each header renders the data for each section itself, and does not rely on a delegate. As a result, calling a header'ssetItemDelegate() function will have no effect.

QTableView

The QTableView class provides a default model/view implementation of a table view.

A QTableView implements a table view that displays items from a model. This class is used to provide standard tables that were previously provided by theQTable class, but using the more flexible approach provided by Qt's model/view architecture.

The QTableView class is one of the Model/View Classes and is part of Qt'smodel/view framework.

QTableView implements the interfaces defined by theQAbstractItemView class to allow it to display data provided by models derived from theQAbstractItemModel class.

Navigation

You can navigate the cells in the table by clicking on a cell with the mouse, or by using the arrow keys.Because QTableView enables tabKeyNavigation by default, you can also hit Tab and Backtab to move from cell to cell.

Visual Appearance

The table has a vertical header that can be obtained using theverticalHeader() function, and a horizontal header that is available through thehorizontalHeader() function. The height of each row in the table can be found by usingrowHeight(); similarly, the width of columns can be found usingcolumnWidth(). Since both of these are plain widgets, you can hide either of them using theirhide() functions.

Rows and columns can be hidden and shown withhideRow(),hideColumn(),

showRow(),andshowColumn(). They can be selected withselectRow() and

selectColumn(). The table will show a grid depending on theshowGrid property.

The items shown in a table view, like those in the other item views, are rendered and edited using standarddelegates. However, for some tasks it is sometimes useful to be able to insert widgets in a table instead. Widgets are set for particular indexes with the setIndexWidget() function, and later retrieved withindexWidget().

By default, the cells in a table do not expand to fill the available space.

You can make the cells fill the available space by stretching the last header section. Access the relevant header usinghorizontalHeader() or

verticalHeader() and set the header'sstretchLastSection property.

To distribute the available space according to the space requirement of each column or row, call the view'sresizeColumnsToContents() or

resizeRowsToContents() functions.

Coordinate Systems

For some specialized forms of tables it is useful to be able to convert between row and column indexes and widget coordinates. TherowAt() function provides the y-coordinate within the view of the specified row; the row index can be used to obtain a corresponding y-coordinate with rowViewportPosition(). ThecolumnAt() and columnViewportPosition() functions provide the equivalent conversion operations between x-coordinates and column indexes.

Styles

QTableView is styled appropriately for each platform. The following images show how it looks on three different platforms. Go to theQt Widget Gallery to see its appearance in other styles.

3、理解。

       QTableWidget类提供了一个灵活的和可编辑的表格控件,包含很多API,可以处理标题、行列、单元格和选中区域,QTableWidget可以嵌入编辑框或显示控件,并可通过拖动控制柄调节各单元格的大小。表格中的每一项可以定义成不同的属性,可以显示文本,可以插入控件,这样就给表格的使用带来了很好的扩展性。

       QTableWidget中单元格包含的内容成为QTableWidgetItem。如果想向QTableWidget中添加文字或图片,则需要先创建一个QTableWidgetItem,然后使用QTableWidget的方法setItem()将其添加到QTableWidget中。当然,如果要对QTableWidget中的任意一个单元格项进行特殊设置,比如字体、颜色等也需要使用QTableWidgetItem。而对于向QTableWidget中添加控件则只需使用QTableWidget的方法setCellWidget()将创建的控件指针作为参数传递进来即可。

QTableView可以使用自定义的数据模型来显示内容(也就是先要通过setModel来绑定数据源),而QTableWidget则只能使用标准的数据模型,并且其单元格数据是QTableWidgetItem的对象来实现的(也就是不需要数据源,将逐个单元格内的信息填好即可)。这主要体现在QTableView类中有setModel成员函数,而到了QTableWidget类中,该成员函数变成了私有。使用QTableWidget就离不开QTableWidgetItemQTableWidgetItem用来表示表格中的一个单元格,正个表格都需要用逐个单元格构建起来。

       4、实例。

QTableWidget * pTableWidget = new QTableWidget( this );

       pTableWidget->setColumnCount( 5 );                 //设置列数

       pTableWidget->setRowCount( 3 );                       //设置行数

      //pTableWidget = new QTableWidget( 5, 3, this );  //带参构造函数

       /*设置列名*/

       QStringList headers;

       headers << tr( "列名1" ) << tr( "列名2" ) <<  tr( "列名3" ) << tr( "列名4" ) << tr( "列名5" ); //乱码???

       pTableWidget->setHorizontalHeaderLabels( headers );

       /*给单元格添加内容*/

       addItemContent( 0, 0, tr( "ad" ) );

       /*给单元格中增加图标*/

       QTableWidgetItem * pItem1 = new QTableWidgetItem( QIcon( ".//Resources//Male.png" ), NULL ); //只加入图标,没有字符串

       QTableWidgetItem * pItem2 = new QTableWidgetItem( QIcon( ".//Resources//Male.png" ), tr( "Male" ) );//加入图标和字符串

       pTableWidget->setItem( 0, 1, pItem1 );

       pTableWidget->setItem( 0, 2, pItem2 );

       /*插入一行*/

       int row = pTableWidget->rowCount();

       pTableWidget->insertRow( row );

       /*插入一列*/

       int column = pTableWidget->columnCount();

       pTableWidget->insertColumn( column );     //设置某一列的标题

       //使行列头自适应宽度,最后一列将会填充空白部分???,注意需要头文件“QHeaderView

       //pTableWidget->horizontalHeader()->setStretchLastSection( true );

       //是行列头自适应宽度,所有列平均分来填充空白部分,注意需要头文件“QHeaderView

       //pTableWidget->horizontalHeader()->setResizeMode( QHeaderView::Stretch );

     //使行自适应高度。假如行很多的话,行的高度不会一直减小,当达到一定值时会自动生成一个QScrollBar,注意需要头文件“QHeaderView

       //pTableWidget->verticalHeader()->setResizeMode( QHeaderView::Stretch );

       //设置单击选择一行,注意需要头文件“QAbstractItemView

       pTableWidget->setSelectionBehavior( QAbstractItemView::SelectRows );

       //设置每行内容不可编辑,注意需要头文件“QAbstractItemView

       //pTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers );

       //设置只能选择一行,不能选择多行,注意需要头文件“QAbstractItemView

       //pTableWidget->setSelectionMode( QAbstractItemView::SingleSelection );

       //去掉每行的行号,注意需要头文件“QHeaderView

       //QHeaderView * pHeaderView = pTableWidget->verticalHeader();

       //pHeaderView->setHidden( true );

       //设置选中某个单元格,注意需要头文件“QItemSelectionModel

       //pTableWidget->setCurrentCell( 0, 1, QItemSelectionModel::Select );

       //设置选中某行,注意需要头文件“QItemSelectionModel

       //pTableWidget->setCurrentCell( 1, QItemSelectionModel::Select );

       //表头的显示与隐藏,注意需要头文件“QHeaderView

       //pTableWidget->verticalHeader()->setVisible( false );           //隐藏列表头,也可通过去掉行号实现

       //pTableWidget->horizontalHeader()->setVisible( false );       //隐藏行表头

       //对表头文字的字体、颜色进行设置

       //QTableWidgetItem * pColumnHeaderItem = pTableWidget->horizontalHeaderItem( 1 );         //获得水平方向表头的Item对象

       //pColumnHeaderItem->setFont( QFont( "Helvetia" ) );                 //设置字体

       //pColumnHeaderItem->setBackgroundColor( QColor( 0, 60, 10 ) );//设置单元格背景颜色

       //pColumnHeaderItem->setTextColor( QColor( 200, 111, 30 ) );   //设置文字颜色

       //pColumnHeaderItem->setText( tr( "Column" ) );

       //在单元格中加入控件

       QComboBox * pComboBox = new QComboBox();

       pComboBox->addItem( tr( "Male" ) );

       pComboBox->addItem( tr( "FeMale" ) );

       pTableWidget->setCellWidget( 1, 0, pComboBox );

     

/********************************************************/

       //设置行和列的大小与内容匹配

       pTableWidget->resize( 700, 500 );        //设置整个表格的大小

       pTableWidget->resizeColumnsToContents();

       pTableWidget->resizeRowsToContents();

       //设置某行或某列的大小

       //pTableWidget->setColumnWidth( 3, 200 );

       //pTableWidget->setRowHeight( 3, 60 );

      

       //合并单元格

       pTableWidget->setSpan( 2, 0, 2, 2 );

       //单元格设置字体颜色和背景颜色 及字体字符

       QTableWidgetItem * pItem3 = new QTableWidgetItem("Apple");

       pItem3->setBackgroundColor( QColor( 0, 60, 10 ) );

       pItem3->setTextColor( QColor( 200, 111, 100 ) );

       pItem3->setFont( QFont( "Helvetica" ) );

       pItem3->setTextAlignment( Qt::AlignCenter );   //设置单元格内文字的对齐方式,如果两种都要设置,只要用 Qt.AlignHCenter | Qt.AlignVCenter 的方式即可

       pTableWidget->setItem( 2, 0, pItem3 );

       //另:如果需要对所有的单元格都使用这种字体,则可以使用 pTableWidget->setFont(QFont("Helvetica"));

       pTableWidget->show();

二、属性。

三、方法。

四、槽函数。

五、信号。

六、静态方法

0 0