alexltr的个人主页

http://www.qtcn.org/bbs/u/107032  [收藏] [复制]

alexltr

我不是IT,只是喜欢Qt。 我不是程序员,只是与程序有缘。

  • 26

    关注

  • 60

    粉丝

  • 150

    访客

  • 等级:骑士
  • 身份:论坛版主
  • 总积分:537
  • 男,1976-01-01
  • 广州

最后登录:2024-04-20

更多资料

日志

Model/View Programming 模型与视图编程 -- <7>

2012-04-29 14:34
Item view convenience classes
项视图简便类


Qt 4 also introduced some standardwidgets to provide classic item-based container widgets. These behave in asimilar way to the item view classes in Qt 3, but have been rewritten to usethe underlying model/view framework for performance and maintainability. Theold item view classes are still available in the compatibility library (see the Porting Guide for more information).

Qt4 同时也引入了一些标准部件以提供传统的基于项的容器部件。这些部件的作用跟Qt3里的项视图类相似,但为了使用底层的模型/视图框架以改善性能以及方便维护,已经对这些类进行了重写。这些旧的项视图类在兼容库中仍然是可用的(详细内容请看 Porting Guide)

The item-based widgets have beengiven names which reflect their uses: QListWidget provides a list of items, QTreeWidget displays a multi-level treestructure, and QTableWidget provides a table of cell items. Eachclass inherits the behavior of the QAbstractItemView class which implements commonbehavior for item selection and header management.
这些基于项的部件已经按他们的用途进行命名:QListWidget提供项的一个列表,QTreeWidget显示多层次树形结构, QTableWidget提供单元格项的一个表格。每一个类都继承基类 QAbstractItemView的行为,这个基类实现了项选择和表头管理等一些常用的行为。

List widgets  
列表部件

Single level lists of items aretypically displayed using a QListWidget and a number of QListWidgetItems. A list widget is constructed inthe same way as any other widget:
单层次列表的项用一个 QListWidget和一些QListWidgetItems来显示。列表部件的构造跟任何其它部件一样:

  1.     QListWidget *listWidget = new QListWidget(this);




List items can be added directly tothe list widget when they are constructed:
列表项可以在构造的时候直接的添加到列表部件中:

  1.      newQListWidgetItem(tr("Sycamore"), listWidget);
         newQListWidgetItem(tr("Chestnut"), listWidget);
         newQListWidgetItem(tr("Mahogany"), listWidget);


They can also be constructed withouta parent list widget and added to a list at some later time:
列表项在构造时也可以不指定父列表部件,而是在之后添加到列表中:

  1.     QListWidgetItem *newItem = new QListWidgetItem;
        newItem->setText(itemText);
        listWidget->insertItem(row, newItem);


Each item in a list can display atext label and an icon. The colors and font used to render the text can bechanged to provide a customized appearance for items. Tooltips, status tips,and "What's This?" help are all easily configured to ensure that thelist is properly integrated into the application.
列表里的每个项都可以显示文字标识和一个图标。表现文字的颜色和字体也可以可以改变,以便为项提供一个自定义的外观。工具提示, 状态栏提示, 以及“这是什么”等帮助功能都可以很容易地设定,以确保这个列表可以完全地跟应用程序融合在一起。

  1.     newItem->setToolTip(toolTipText);
        newItem->setStatusTip(toolTipText);
        newItem->setWhatsThis(whatsThisText);


By default, items in a list arepresented in the order of their creation. Lists of items can be sortedaccording to the criteria given in Qt::SortOrder to produce a list of items that issorted in forward or reverse alphabetical order:
默认情况下,列表里的项按照他们创建时的顺序来显示。列表项可以按照Qt::SortOrder指定的规则进行排序,以产生一个按升序或降序排列的列表:

  1.    listWidget->sortItems(Qt::AscendingOrder);
        listWidget->sortItems(Qt::DescendingOrder);


Tree widgets
树形部件

Trees or hierarchical lists of items are providedby the QTreeWidget and QTreeWidgetItem classes. Each item in thetree widget can have child items of its own, and can display a number ofcolumns of information. Tree widgets are created just like any other widget:
树形或层次结构型的列表项由QTreeWidget 和QTreeWidgetItem类提供。树形部件里的每个项都可以有它们自己的子项,同时也可以显示多列信息。树形部件的创建跟其它部件一样:

  
  1. QTreeWidget *treeWidget = new QTreeWidget(this);

Before items can be added to the tree widget, thenumber of columns must be set. For example, we could define two columns, andcreate a header to provide labels at the top of each column:
在把项加到树形部件之前,必须先设定列数。例如,我们可以定义两列,然后创建一个表头,以便在每一列的顶部提供一个标识:
  1.    treeWidget->setColumnCount(2);
        QStringList headers;
         headers<< tr("Subject") << tr("Default");
        treeWidget->setHeaderLabels(headers);

The easiest way to set up the labelsfor each section is to supply a string list. For more sophisticated headers,you can construct a tree item, decorate it as you wish, and use that as thetree widget's header.
为每一列建立标识最容易的方法就是提供一个字符串列表。至于更为复杂的表头,你可以构造一个树形项,按照你的要求进行布置,并把它作为树形部件的表头来使用。

Top-level items in the tree widgetare constructed with the tree widget as their parent widget. They can beinserted in an arbitrary order, or you can ensure that they are listed in aparticular order by specifying the previous item when constructing each item:
树形部件的顶级项以树形部件作为它们的父部件来构造。它们可以以任意的顺序插入,或者在构造每个项时,你可以通过指定前一个项来确保以特定的顺序列出这些项:

  1.     QTreeWidgetItem *cities = new QTreeWidgetItem(treeWidget);
         cities->setText(0,tr("Cities"));
        QTreeWidgetItem *osloItem = new QTreeWidgetItem(cities);
        osloItem->setText(0, tr("Oslo"));
        osloItem->setText(1, tr("Yes"));

        QTreeWidgetItem *planets = new QTreeWidgetItem(treeWidget, cities);


Tree widgets deal with top-levelitems slightly differently to other items from deeper within the tree. Itemscan be removed from the top level of the tree by calling the tree widget's takeTopLevelItem() function, but items from lower levelsare removed by calling their parent item's takeChild() function. Items are inserted in thetop level of the tree with the insertTopLevelItem() function. At lower levels in the tree,the parent item's insertChild() function is used.
树形部件处理顶层项的方法跟处理其它层次的项的方法稍有不同。它的顶层项可以通过调用树形部件的takeTopLevelItem()函数来进行删除,而其它低层次的项要通过调用它们父项的 takeChild()函数来进行删除。顶层项的插入用insertTopLevelItem() 函数,而其它层次的项要用父项的 insertChild()函数来插入。

It is easy to move items aroundbetween the top level and lower levels in the tree. We just need to checkwhether the items are top-level items or not, and this information is suppliedby each item's parent() function. For example, we can removethe current item in the tree widget regardless of its location:
   在树型部件的顶层项及其它层级的项之间移动是很容易的。我们只需检测这些项是否是顶层项,这个信息由每个项的parent()函数提供。比如,我们可以删除树形部件里的当前项,而不用去管它的具体位置是什么:

  1.    QTreeWidgetItem *parent = currentItem->parent();
         intindex;

         if(parent) {
            index = parent->indexOfChild(treeWidget->currentItem());
            delete parent->takeChild(index);
         } else{
            index =treeWidget->indexOfTopLevelItem(treeWidget->currentItem());
            delete treeWidget->takeTopLevelItem(index);
         }


Inserting the item somewhere else inthe tree widget follows the same pattern:
把项插入到树形部件的某个位置也是使用一样的模式:


  1.    QTreeWidgetItem *parent = currentItem->parent();
        QTreeWidgetItem *newItem;
         if(parent)
             newItem = new QTreeWidgetItem(parent,treeWidget->currentItem());
         else
            newItem = new QTreeWidgetItem(treeWidget, treeWidget->currentItem());



Table widgets  
表格部件

Tables of items similar to thosefound in spreadsheet applications are constructed with the QTableWidget and QTableWidgetItem. These provide a scrolling tablewidget with headers and items to use within it.
Tables can be created with a setnumber of rows and columns, or these can be added to an unsized table as theyare needed.
表格部件跟电子制表程序里用到的相似,都是用QTableWidget 和 QTableWidgetItem构造。它们提供一个带表头的可滚动表格,而把项置于其中来使用。
在构建表格部件时可以指定行数和列数,未定义大小的表格部件也可以在需要的时候再加上行数和列数。

  1.     QTableWidget *tableWidget;
        tableWidget = new QTableWidget(12, 3, this);

Items are constructed outside thetable before being added to the table at the required location:
项可以在添加到表格的指定位置之前,在表格之外单独构造:

  1.     QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1").arg(pow(row, column+1)));
        tableWidget->setItem(row, column, newItem);


Horizontal and vertical headers canbe added to the table by constructing items outside the table and using them asheaders:
通过在表格外构造项,并把它们作为表头使用,就可以添加表格的水平和垂直表头:

  1.     QTableWidgetItem *valuesHeaderItem = newQTableWidgetItem(tr("Values"));
        tableWidget->setHorizontalHeaderItem(0, valuesHeaderItem);



Note that the rows and columns in thetable begin at zero.
注意,表格的行号和列号是从0开始的。

Common features  
共有特性

There are a number of item-basedfeatures common to each of the convenience classes that are available throughthe same interfaces in each class. We present these in the following sectionswith some examples for different widgets. Look at the list of Model/View Classes for each of the widgets for moredetails about the use of each function used.
有几个基于项的特性是每个项视图简便类共有的,它们都可以通过每个类的相同接口来进行使用。接下来的几个小节我们将通过使用不同背景的几个例子来说明这些特性。对于所使用到得函数,可以通过查看 Model/View Classes列表中的每个部件来获得更详细的内容。

Hidden items  
隐藏项

It is sometimes useful to be able tohide items in an item view widget rather than remove them. Items for all of theabove widgets can be hidden and later shown again. You can determine whether anitem is hidden by calling the isItemHidden() function, and items can be hiddenwith setItemHidden().
Since this operation is item-based,the same function is available for all three convenience classes.
有时需要在一个项视图部件中隐藏项,而不是删除项。以上所有部件的项都可以隐藏和重现。你可以通过调用isItemHidden()函数知道一个项是否被隐藏,同时用setItemHidden()函数可以将项隐藏。
因为这个操作是基于项的,所以相同的函数适用于所有简便类。

Selections  
选择

The way items are selected iscontrolled by the widget's selection mode (QAbstractItemView::SelectionMode).This property controls whether the user can select one or many items and, inmany-item selections, whether the selection must be a continuous range ofitems. The selection mode works in the same way for all of the above widgets.
项的选择方式由部件的选择模式(QAbstractItemView::SelectionMode)控制。这个属性控制用户是否可以选择一个或多个项,如果是多项选择,选择是否必须是一个连续的项范围。以上所有部件的选择模式的工作方式都是一样的。

Single itemselections: Where the userneeds to choose a single item from a widget, the default SingleSelection mode is most suitable. In thismode, the current item and the selected item are the same.
单项选择:当用户需要在一个部件中选择一个单一项时,默认的SingleSelection模式是最适合的。这种模式的当前项和选择的项是一样的。

Multi-item selections: In this mode, the usercan toggle the selection state of any item in the widget without changing theexisting selection, much like the way non-exclusive checkboxes can be toggledindependently.
多项选择:使用这种模式,用户可以在不改变当前选择的情况下切换这个部件中任意项的选择状态,跟非排他性的复选框单独切换的方式很相似的。

Extended selections: Widgets that oftenrequire many adjacent items to be selected, such as those found inspreadsheets, require the ExtendedSelection mode. In this mode,continuous ranges of items in the widget can be selected with both the mouseand the keyboard. Complex selections, involving many items that are notadjacent to other selected items in the widget, can also be created ifmodifier keys are used.
If the user selects an item without using amodifier key, the existing selection is cleared.
扩展选择:需要选择许多相邻项的部件,如电子制表,就要使用到扩展选择模式ExtendedSelection。使用这种模式,部件里连续范围的项可以同时用鼠标和键盘进行选择。如果使用修改键,也可以创建复杂的选择,如涉及到部件里跟其它选中的的项不相邻的多个项的选择。
如果用户在选择一个项时没有使用修改键,那原来的选择就会被清除。

The selected items in a widget areread using the selectedItems() function, providing a list ofrelevant items that can be iterated over. For example, we can find the sum ofall the numeric values within a list of selected items with the following code:
部件中被选中的项可以用 selectedItems()函数来读取,它提供一个可以历遍的相关项的列表。例如,我们可以用下面的代码找出一个选择项列表中所有数值的总和:
  1.      QList<QTableWidgetItem*> selected = tableWidget->selectedItems();
        QTableWidgetItem *item;
         intnumber = 0;
         doubletotal = 0;

         foreach(item, selected) {
            bool ok;
            double value = item->text().toDouble(&ok);

             if(ok && !item->text().isEmpty()) {
                total += value;
                number++;
             }
         }

Note that for the single selectionmode, the current item will be in the selection. In the multi-selection andextended selection modes, the current item may not lie within the selection,depending on the way the user formed the selection.
注意,对于单选模式,当前项是被选中的。而对于多选模式和扩展模式,当前项不一定在选择范围内,这要看用户选择的方式

Searching
搜索

It is often useful to be able to finditems within an item view widget, either as a developer or as a service topresent to users. All three item view convenience classes provide a common findItems() function to make this as consistentand simple as possible.
Items are searched for by the textthat they contain according to criteria specified by a selection of values from Qt::MatchFlags. We can obtain a list ofmatching items with the findItems() function:
无论是作为一个开发人员还是作为一项面向用户的服务,能够在一个项视图中找出项总是会很有帮助的。所有3种项视图简便类提供了一个通用的findItems()函数,使得这个功能可以尽可能的一致和简单。
项是以Qt::MatchFlags中的一个值所指定的规则,按照项的文字进行搜索的。我们可以用findItems()函数得到一个符合要求的项的列表。

  1.     QTreeWidgetItem *item;
        QList<QTreeWidgetItem *> found = treeWidget->findItems(
            itemText, Qt::MatchWildcard);

         foreach(item, found) {
            treeWidget->setItemSelected(item, true);
             [i][color=#8b0000]// Showthe item->text(0) for each item.[/color][/i]
         }



The above code causes items in a treewidget to be selected if they contain the text given in the search string. Thispattern can also be used in the list and table widgets.
上面的代码得到的结果是,树形部件中的项如果包含搜索字符串中的文字就会被选中。这个模式同样可以应用于列表部件和表格部件。

Using drag & drop with item views  
项视图的拖放

Qt's drag and drop infrastructure isfully supported by the model/view framework. Items in lists, tables, and treescan be dragged within the views, and data can be imported and exported asMIME-encoded data.
模型/视图框架完全支持Qt的拖放基础。列表,表格,树形部件中的项可以在视图间拖动,数据可以以MIME类型的格式进行导入和导出。

The standard views automaticallysupport internal drag and drop, where items are moved around to change theorder in which they are displayed. By default, drag and drop is not enabled forthese views because they are configured for the simplest, most common uses. Toallow items to be dragged around, certain properties of the view need to beenabled, and the items themselves must also allow dragging to occur.
标准视图自动支持内部的拖放,他们的项可以被移动以改变他们的显示顺序。默认情况下,这些视图是不能进行拖放操作的,因为他们被设定成最简单最常用的用法。如果要拖动项,则要开启视图的一些属性,并且项本身也必须是允许拖动的。

The requirements for a model thatonly allows items to be exported from a view, and which does not allow data tobe dropped into it, are fewer than those for a fully-enabled drag and dropmodel.
See also the Model Subclassing Reference for more information about enablingdrag and drop support in new models.
相比那些完全支持拖放的模型,只允许项从一个视图中导出,而不允许数据放入到其中的模型是很少的。
更多关于在新模型中启用拖放支持的内容,请看子类化模型参考这一章节。

Usingconvenience views  
简便类视图的使用

Each of the types of item used with QListWidget, QTableWidget,and QTreeWidget is configured to use a different set of flags by default. Forexample, eachQListWidgetItem or QTreeWidgetItem is initially enabled, checkable, selectable, and can be used as thesource of a drag and drop operation; eachQTableWidgetItem can also be edited and used as the target of a drag and dropoperation.
QListWidget, QTableWidget,和 QTreeWidget的每一种类型的项都默认配置有一套不同的标识。比如,QListWidgetItem或 QTreeWidgetItem的初始标识是启用的enabled, 可复选的checkable,可选择的 selectable,同时可以作为拖放操作的数据源;QTableWidgetItem可以进行编辑操作,并且可以作为拖放操作的目标。

Although all of the standard items have one orboth flags set for drag and drop, you generally need to set various propertiesin the view itself to take advantage of the built-in support for drag and drop:
虽然所有的标准项都有一或两个标识用于拖放操作,但是你还是要在视图本身设置不同的属性,以利用内置的拖放支持。

l  To enable item dragging, set theview's dragEnabled property to true.
要启用项的拖动,就要把视图的dragEnabled 属性设定为true

l  To allow the user to drop eitherinternal or external items within the view, set the view's viewport()'s acceptDrops propertyto true.
要允许用户将内部或外部项拖放到视图中,则要把视图的viewport()的 acceptDrops 属性设定为true。

l  To show the user where the itemcurrently being dragged will be placed if dropped, set the view's showDropIndicator property. This provides the user withcontinuously updating information about item placement within the view.
要显示当前拖动的项将被放在什么地方,则要设定视图的showDropIndicator属性。它会提供关于项在视图中的放置位置的持续更新信息。

For example, we can enable drag and drop in a listwidget with the following lines of code:
例如,我们可以用以下代码在列表部件中启用拖放功能。

  1. QListWidget*listWidget = new QListWidget(this);
    listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    listWidget->setDragEnabled(true);
    listWidget->viewport()->setAcceptDrops(true);
    listWidget->setDropIndicatorShown(true);


The result is a list widget which allows the itemsto be copied around within the view, and even lets the user drag items betweenviews containing the same type of data. In both situations, the items arecopied rather than moved.
这样就得到一个可以让项在视图里进行复制的列表部件,甚至可以让用户在包含相同类型数据的视图间拖动项。这两种情况,项是被复制而不是移动。

To enable the user to move the items around withinthe view, we must set the list widget's dragDropMode:
如果用户要在视图间移动项,那我们就要设定列表部件的拖放模式dragDropMode。

  1. listWidget->setDragDropMode(QAbstractItemView::InternalMove);


分类:默认分类|回复:0|浏览:3875|全站可见|转载
 

Powered by phpwind v8.7 Certificate Copyright Time now is:04-28 01:19
©2005-2016 QTCN开发网 版权所有 Gzip disabled