QT in QListWidget

Qt the assembly for item (Item) process there are two types, one is Item Views, including QListView, QTreeView, QTableView, QColumnView; the other is Item Widgets, including QListWidget, QTreeWidget and QTable Widget.

Display and editing, using the model / view showing a structure of Item Views for data based on the model / view (Model / View) configuration view (View) and the model data (Model Data) associated described in detail in the following sections.

Item Widgets data directly stored in each item in, for example, each row is a QListWidget entries, each entry is a node QTreeWidget, each cell is a QTableWidget item. A term storage of text, text formatting, custom data.

Item Widgets GUI design is commonly used in assembly, by way of example in this section describes the use QListWidget samp4_7 first and other components, the interface shown in FIG. 1 runtime instance.


Examples Samp4_7 runtime interface
Example 1 FIG runtime interface Samp4_7


This example only describes the use QListWidget, further comprising a number of functions to achieve the following:

  • Use QTabWidget design multi-page interface, the right side of the work area is a TabWidget component has three pages.
  • QToolBox use multiple sets of design toolbox left of the workspace is a component ToolBox three groups.
  • Use divider (QSplitter) designed to split the left and right interface between a splitter and a work area ToolBox TabWidget, two components may be divided to adjust the size of the runtime.
  • Creating Actions, Actions with the design of the main toolbar, associated with Action QToolButton button.
  • Use QToolButton button, set associated with the Action, designed with ToolButton button drop-down menu functions, add Tooffiutton button has a pull-down menu on the main toolbar.
  • Use QListWidget, demonstrates how to create and add items, check boxes and set the icon for the item, how to traverse the list to choose.
  • CurrentItemChanged QListWidget the primary signal () function, written in response to the slot function.
  • It has been designed for use QListWidget Components Actions to create a custom shortcut menu.

interface design

Hybrid interface design

The main window of the present example QMainWindow inherited from using a hybrid interface design. Done in the UI designer in the form interface shown in Figure 2, there are some differences with the operation of the interface shown in Figure 1. Runtime adds a toolbar button with a drop-down menu in the toolbar, set the Action associated for each ToolButton button.


Done in the UI designer in the form interface
FIG 2 is completed in the UI designer form interface


Button on the interface in FIG. 2 are used QToolButton assembly, designed to name only, FIG text which is displayed on the button objectName. QToolButton have a setDefaultAction () function, it may be associated with an Action, text buttons, icons, ToolTip slot function will automatically be set to coincide with the associated Action, click a button QToolButton is the implementation of the Action, on the toolbar Like button. In fact, QToolButton button button on the main toolbar, according to Action is automatically created.

Another QToolButton SetMenu () function, can set up a drop-down menus, with some property QToolButton, the pull-down menu can have different effects. In Figure 1, the "choice" is displayed directly on the toolbar drop-down menu, and in the "options" button at the top of the list box, just click the down arrow to the right before the pop-up drop-down menu, click the button will execute directly Action button code associated with it.

Part of a hybrid interface design implemented by the code, is provided for the ToolButton associated Action button on the interface, on the toolbar dynamically add a ToolButton, and set its drop-down menu function.

Set QToolBox components

When the design surface, placing a QToolBox assembly workspace window in the UI designer.

Component ToolBox call up the context menu, you can use the "Insert Page" "Delete Page" and other menu items to add or delete achieve packet. Click the title of a group, you can choose for the current packet ToolBox component, in the Property Editor main attributes are set as follows:

  • currentlndex: current packet number, a packet numbering is 0, by changing this value, select a different page groups.
  • currentltemText: current packet header.
  • currentltemName: Object name of the current packet.
  • currentltemlcon: an icon for the current group settings, text is displayed in the left side of the title.


It can be placed in a ToolBox any interface components, such as QGroupBox, QLineEdit, QPushButton like. QToolButton place several buttons in the first packet, and set Grid layout. Be careful not to use horizontal layout, because when using a horizontal layout, ToolButton button in the group are automatically aligned by the left, and the use of Grid layout, automatically centered.

Set QTabWidget components

QTabWidget component class is a container of a multi-page. Place a QTabWidget assembly on the window, through the "Insert Page" its shortcut menu, "Delete Page" and other menu items to achieve the page to add or remove.

In the Property Editor main attributes are set as follows:

  • tabPosition: Location page labels, east, west, south and north orientation select one.
  • currentlndex: The current page number.
  • currentTabText: current title page.
  • currentTabName: current object name of the page.
  • currentTablcon: You can set an icon for the current page, the title of the text displayed on the left.

Use QSplitter split interface design

Typical segmentation interface has a Windows Explorer, QSplitter for interface design has the effect of segmentation can be split horizontally or vertically.

This example of the main window are two main components and toolBox tabWidget, hope that these two components are designed to effect approximately segmentation. Select both components, click "Lay Out Horizontally in Splitter" button, you can on the main window toolbar These two components create a horizontal layout component splitter split. Use the following line in the main window constructor can make the splitter filled up the entire work area:

setCentralWidget(ui->splitter);

When using splitter resize, you do not want ToolBox width becomes too small to affect the display buttons may be provided minimumSize.Width properties toolBox is provided a minimum width.

QListWidget settings

QListWidget placing a component, and a few other buttons and edit boxes on a page TabWidget first component, the composition of the interface shown in FIG. QListWidget list of components is stored in a plurality of entries, each entry is an object QListWidgetltem type.

Double-ListWidget component, which can open the list item editor, as shown in FIG. This can increase the editor, delete, move up, move down the list of items, you can set the properties of each item, including text, font, text alignment, background color, foreground color and so on.


QListWidget component list item editor
3 QListWidget assembly list item editor FIG.


Which is more important attribute flags (FIG. 3), used in some settings of the flag, which is an enumerated type markers specific value Qt :: ItemFlag, comprising the following:

  • Selectable: whether the item can be selected, the corresponding enumeration value Qt :: ItemIsSelectable.
  • Editable: whether the item can be edited, the corresponding enumeration value Qt :: ItemlsEditable.
  • DragEnabled: whether the item can be dragged, the corresponding enumeration value Qt :: ItemlsDragEnabled.
  • DropEnabled: whether the item can drag and drop the item received corresponding enumeration value Qt :: ItemlsDropEnabled.
  • UserCheckable: whether the item can be checked, if it is true, an entry appears in front of the CheckBox, corresponding to the enumeration value Qt :: ItemlsUserCheckable.
  • Enabled: whether the item is enabled, the corresponding enumeration value Qt :: ItemlsEnabled.
  • Tristate: Check whether to allow a third state, if it is false, then checked and unchecked only two states, corresponding to the enumeration value Qt :: ItemIsAutoTristate.


在代码中设置项的 flags 属性时,使用函数 setFlags(),例如:

aItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable IQt::ItemIsEnabled);

QListWidget 的列表项一般是在程序里动态创建,后面会演示如何用程序完成添加、删除列表项等操作。

创建 Action

前面章节中己经介绍了创建 Action,学习用 Action 设计主菜单和主工具栏的方法。本实例也采用 Action 设计工具栏,并且将 Action 用于 QToolButton 按钮。创建的 Action 列表如图 4 所示。利用这些 Action 创建主工具栏,设计时完成的主工具栏如图 2 所示。


Action in this instance created
图 4 本实例创建的Action


actSelPopMenu 用于“项选择”的ToolButton按钮,也就是窗口上具有下拉菜单的两个按钮。将 actSelPopMenu 的功能设置为与 actSelInvs 完全相同,在“Signals &Slots Editor”里设置这两个 Action 关联(如图 5 所示),这样,执行 actSelPopMenu 就是执行 actSellnvs。


Signals provided in association editor and Slots
图 5 在 Signals 和 Slots 编辑器中设置的关联

 

 

QListWidget 的操作

初始化列表

actListIni 实现 listWidget 的列表项初始化,其 trigger() 信号槽函数代码如下:

 
  1. void MainWindow::on_actListIni_triggered()
  2. { //初始化项
  3. QListWidgetItem *aItem; //每一行是一个QListWidgetItem
  4.  
  5. QIcon aIcon;
  6. aIcon.addFile(":/images/icons/check2.ico"); //设置ICON的图标
  7. bool chk=ui->chkBoxListEditable->isChecked();//是否可编辑
  8.  
  9. ui->listWidget->clear(); //清除项
  10. for (int i=0; i<10; i++)
  11. {
  12. QString str=QString::asprintf("Item %d",i);
  13. aItem=new QListWidgetItem(); //新建一个项
  14.  
  15. aItem->setText(str); //设置文字标签
  16. aItem->setIcon(aIcon);//设置图标
  17. aItem->setCheckState(Qt::Checked); //设置为选中状态
  18. if (chk) //可编辑, 设置flags
  19. aItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
  20. else//不可编辑, 设置flags
  21. aItem->setFlags(Qt::ItemIsSelectable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
  22. ui->listWidget->addItem(aItem); //增加一个项
  23. }
  24. }

列表框里一行是一个项,是一个 QListWidgetltem 类型的对象,向列表框添加一个项,就需要创建一个 QListWidgetltem 类型的实例 aItem,然后设置 aItem 的一些属性,再用 QListWidget::AddItem() 函数将该 aItem 添加到列表框里。

QListWidgetItem 有许多函数方法,可以设置项的很多属性,如设置文字、图标、选中状态,还可以设置 flags,就是图 3 对话框里设置功能的代码化。

插入项

插入项使用 QListWidget 的 insertItem(int row, QListWidgetItem *item) 函数,在某一行 row 的前面插入一个 QListWidgetItem 对象 item,也需要先创建这个 item,并设置好其属性。actListInsert 实现这个功能,其槽函数代码如下:

 
  1. void MainWindow::on_actListInsert_triggered()
  2. { //插入一个项
  3. QIcon aIcon;
  4. aIcon.addFile(":/images/icons/check2.ico"); //图标
  5.  
  6. bool chk=ui->chkBoxListEditable->isChecked();
  7. QListWidgetItem* aItem=new QListWidgetItem("New Inserted Item"); //创建一个项
  8. aItem->setIcon(aIcon);//设置图标
  9. aItem->setCheckState(Qt::Checked); //设置为checked
  10. if (chk) //设置标记
  11. aItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
  12. else
  13. aItem->setFlags(Qt::ItemIsSelectable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
  14. ui->listWidget->insertItem(ui->listWidget->currentRow(),aItem); //在当前行的上方插入一个项
  15. }

这里设置新插入的项是可选择的、能用的、可复选的。还根据界面设置,确定项是否可编辑。

删除当前项和清空列表

删除当前项的 actListDelete 的槽函数代码如下:

 
  1. void MainWindow::on_actListDelete_triggered()
  2. { //删除当前项
  3. int row=ui->listWidget->currentRow();//当前行
  4. QListWidgetItem* aItem=ui->listWidget->takeItem(row); //移除指定行的项,但不delete
  5. delete aItem; //需要手工删除对象
  6. }

takeItem() 函数只是移除一个项,并不删除项对象,所以还需要用 delete 从内存中删除它。要清空列表框的所有项,只需调用 QListWidget::clear() 函数即可。

遍历并选择项

界面上有“全选” “全不选” “反选” 3 个按钮,由 3 个 Action 实现,用于遍历列表框里的项,设置选择状态。用于“全选”的 actSelALL 的槽函数代码如下:

 
  1. void MainWindow::on_actSelALL_triggered()
  2. { //项全选
  3. // QListWidgetItem *aItem; //项对象
  4. int cnt=ui->listWidget->count();//项个数
  5. for (int i=0; i<cnt; i++)
  6. {
  7. QListWidgetItem *aItem=ui->listWidget->item(i);//获取一个项
  8. aItem->setCheckState(Qt::Checked);//设置为选中
  9. }
  10. }

函数 QListWidgetItem::setCheckState(Qt::CheckState state) 设置列表项的复选状态,枚举类型 Qt::CheckState 有 3 种取值:

  1. Qt::Unchecked:不被选中。
  2. Qt::PartiallyChecked:部分选中。在目录树中的节点可能出现这种状态,比如其子节点没有全部被勾选时。
  3. Qt::Checked:被选中。

QListWidget的常用信号

QListWidget 在当前项切换时发射两个信号,只是传递的参数不同:

  • currentRowChanged(int currentRow):传递当前项的行号作为参数。
  • currentItemChanged(QListWidgetItem * current, QListWidgetItem * previous):传递两个 QList Widgetltem对象作为参数,current表示当前项,previous是前一项。


当前项的内容发生变化时发射信号 currentTextChanged(const QString &currentText)。

为 listWidget 的 currentItemChanged() 信号编写槽函数,代码如下:

 
  1. void MainWindow::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
  2. { //listWidget当前选中项发生变化
  3. QString str;
  4. if (current != NULL) //需要检测变量指针是否为空
  5. {
  6. if (previous==NULL) //需要检测变量指针是否为空
  7. str="当前:"+current->text();
  8. else
  9. str="前一项:"+previous->text()+"; 当前项:"+current->text();
  10. ui->editCutItemText->setText(str);
  11. }
  12. }

响应代码里需要判断 current 和 previous 指针是否为空,否则使用对象时可能出现访问错误。

QToolButton与下拉式菜单

QToolButton 关联 QAction

图 2 所示的界面上,在 ToolBox 里放置了几个 QToolButton 按钮,希望它们实现与工具栏上的按钮相同的功能;列表框上方放置了几个 QToolButton 按钮,希望它们完成列表项选择的功能。

这些功能都己经有相应的 Actions 来实现,要让 ToolButton 按钮实现这些功能,无需再为其编写代码,只需设置一个关联的 QAction 对象即可。

QToolButton 有一个函数 setDefaultAction(),其函数原型为:

void QToolButton: :setDefaultAction(QAction * action)

使用 setDefaultAction() 函数为一个 QToolButton 按钮设置一个 Action 之后,将自动获取 Action 的文字、图标、ToolTip 等设置为按钮的相应属性。所以,在界面设计时无需为 QToolButton 做过多的设置。

在主窗体类里定义一个私有函数 setActionsForButton(),用来为界面上的 QToolButton 按钮设置关联的 Actions,setActionsForButton() 在主窗口的构造函数里调用,其代码如下:

 
  1. void MainWindow::setActionsForButton()
  2. { //为 QToolButton 按钮设置 Action
  3. ui->tBtnListIni->setDefaultAction(ui->actListIni);
  4. ui->tBtnListClear->setDefaultAction(ui->actListClear);
  5. ui->tBtnListInsert->setDefaultAction(ui->actListInsert);
  6. ui->tBtnListAppend->setDefaultAction(ui->actListAppend);
  7. ui->tBtnListDelete->setDefaultAction(ui->actListDelete);
  8.  
  9. ui->tBtnSelALL->setDefaultAction(ui->actSelALL);
  10. ui->tBtnSelNone->setDefaultAction(ui->actSelNone);
  11. ui->tBtnSelInvs->setDefaultAction(ui->actSelInvs);
  12. }

在程序启动后,界面上的 ToolButton 按钮自动根据关联的 Actions 设置其按钮文字、图标和 ToolTip。单击某个 ToolButton 按钮,就是执行了其关联的 Action 的槽函数代码。使用 Actions 集中设计功能代码,用于菜单、工具栏、ToolButton 的设计,是避免重复编写代码的一种方式。

为QToolButton按钮设计下拉菜单

还可以为 QToolButton 按钮设计下拉菜单,在图 1 的运行窗口中,单击工具栏上的“项选择”按钮,会在按钮的下方弹出一个菜单,有 3 个菜单项用于项选择。

在主窗口类里定义一个私有函数 createSelectionPopMenu(),并在窗口的构造函数里调用,其代码如下:

 
  1. void MainWindow::createSelectionPopMenu()
  2. {
  3. //创建下拉菜单
  4. QMenu* menuSelection=new QMenu(this); //创建选择弹出式菜单
  5. menuSelection->addAction(ui->actSelALL);
  6. menuSelection->addAction(ui->actSelNone);
  7. menuSelection->addAction(ui->actSelInvs);
  8.  
  9. //listWidget上方的tBtnSelectItem按钮
  10. ui->tBtnSelectItem->setPopupMode(QToolButton::MenuButtonPopup);//菜单弹出模式,执行按钮的Action
  11. ui->tBtnSelectItem->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //按钮样式
  12. ui->tBtnSelectItem->setDefaultAction(ui->actSelPopMenu);//关联Action
  13. ui->tBtnSelectItem->setMenu(menuSelection); //设置下拉菜单
  14.  
  15. //工具栏上的 下拉式菜单按钮
  16. QToolButton *aBtn=new QToolButton(this);
  17. aBtn->setPopupMode(QToolButton::InstantPopup);//button's own action is not triggered.
  18. aBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);//按钮样式
  19. aBtn->setDefaultAction(ui->actSelPopMenu); //设置Action,获取图标、标题等设置
  20. aBtn->setMenu(menuSelection);//设置下拉菜单
  21. ui->mainToolBar->addWidget(aBtn); //工具栏添加按钮
  22.  
  23. //工具栏添加分隔条,和“退出”按钮
  24. ui->mainToolBar->addSeparator();
  25. ui->mainToolBar->addAction(ui->actQuit);
  26. }

这段代码首先创建一个 QMenu 对象 menuSelection,将 3 个用于选择列表项的 Action 添加作为菜单项。

tBtnSelectItem 是窗体上 ListWidget 上方具有下拉菜单的 QToolButton 按钮的名称,调用了 QToolButton 类的 4 个函数对其进行设置:

  1. setPopupMode(QToolButton::MenuButtonPopup):设置其弹出菜单的模式。QToolButton::MenuButtonPopup 是一个枚举常量,这种模式下,按钮右侧有一个向下的小箭头,必须单击这个小按钮才会弹出下拉菜单,直接单击按钮会执行按钮关联的 Action,而不会弹出下拉菜单。
  2. setToolButtonStyle(Qt::ToolButtonTextBesidelcon):设置按钮样式,按钮标题文字在图标右侧显示。
  3. setDefaultAction(ui->actSelPopMenu):设置按钮的关联 Action,actSelPopMenu 与 actSellnvs有信号与槽的关联,所以,直接单击按钮会执行“反选”的功能。
  4. setMenu(menuSelection):为按钮设置下拉菜单对象。


工具栏上具有下拉菜单的按钮需要动态创建。先创建 QToolButton 对象 aBtn,同样用以上 4 个函数进行设置,但是设置的参数稍微不同,特别是设置弹出菜单模式为:

aBtn->setPopupMode(QToolButton::InstantPopup)

这种模式下,工具按钮的右下角显示一个小的箭头,单击按钮直接弹出下拉菜单,即使为这个按钮设置了关联的 Action,也不会执行 Action 的功能。这是这两个具有下拉菜单的 QToolButton 按钮的区别。

setActionsForButton()和createSelectionPopMenu() 函数在窗口的构造函数里调用,构造函数的完整代码如下:

 
  1. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
  2. {
  3. ui->setupUi(this);
  4. setCentralWidget(ui->splitter);
  5. setActionsForButton();
  6. createSelectionPopMenu();
  7. }

创建右键快捷菜单

每个从 QWidget 继承的类都有信号 customContextMenuRequested(),这个信号在鼠标右击时发射,为此信号编写槽函数,可以创建和运行右键快捷菜单。

本实例为 listWidget 组件的 customContextMenuRequested() 信号创建槽函数,实现快捷菜单的创建与显示,代码如下:

 
  1. void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
  2. {
  3. Q_UNUSED(pos);
  4. QMenu* menuList=new QMenu (this) ; //创建菜单
  5. //添加Actions创建菜单项
  6. menuList->addAction(ui->actListIni);
  7. menuList->addAction(ui->actListClear);
  8. menuList->addAction(ui->actListInsert);
  9. menuList->addAction(ui->actL±stAppend);
  10. menuList->addAction(ui->actListDelete);
  11. menuList->addSeparator();
  12. menuList->addAction(ui->actSelALL);
  13. menuList->addAction(ui->actSelNone);
  14. menuList->addAction(ui->actSelInvs);
  15. menuList-> exec (QCursor :: pos ()); // display the context menu in the mouse cursor position
  16. delete menuList;
  17. }

In this code, the first type of objects to create a QMenu menuList, and then use QMenu of addAction () method has been designed to add Actions as a menu item.

After creating the menu, use QMenu :: exec () function to display the shortcut menu:

menuList->exec(QCursor::pos());

This will display a pop-up menu at the current mouse position, static function QCursor :: pos () to get the mouse cursor's current position. Operating results of the shortcut menu as shown in FIG.


listWidget 组件的右键快捷菜单的运行效果
Operating results of the context menu 6 listWidget assembly of FIG.

Published 21 original articles · won praise 2 · Views 2198

Guess you like

Origin blog.csdn.net/conimade/article/details/104396494