C++ Qt development: ListWidget list box component

Qt is a cross-platform C++ graphical interface development library. You can use Qt to quickly develop cross-platform form applications. In Qt, we can drag and drop different components into designated locations to achieve great convenience in graphical development. For the sake of development efficiency, this chapter will focus on ListWidgetthe common methods and flexible application of list box components.

QListWidgetIt is a list box component in Qt that displays a list of items and allows the user to make selections. Each item can contain an icon and text, which can be QListWidgetItemrepresented using classes. ListWidgetThe component is TreeWidgetsomewhat similar to the component. The difference is that TreeWidgetit can implement nested and multi-field structures, while ListWidgetit can only implement a single-field structure. This component is often used to display a single record, such as only displaying IPaddress, user name and other data.

Here are QListWidgetsome common methods of the class, description and overview:

method describe
addItem(QListWidgetItem *item) Add an item to the list.
addItems(const QStringList &labels) Add multiple items to the list.
count() Returns the number of items in the list.
currentItem() Returns the currently selected item.
item(int row) Returns the item at the given row index.
itemAt(const QPoint &p) Returns the item at the given coordinates.
takeItem(int row) Removes and returns the item at the given row index from the list.
clear() Remove all items from the list.
clearSelection() Deselect all items.
removeItemWidget(QListWidgetItem *item) Removes an item from the list and releases any widgets associated with it.
scrollToItem(QListWidgetItem *item, QAbstractItemView::ScrollHint hint = EnsureVisible) Scroll the list to ensure a given item is visible.
sortItems(Qt::SortOrder order = Qt::AscendingOrder) Sort items in a list.
itemClicked(QListWidgetItem *item) Signal emitted when an item is clicked.
itemDoubleClicked(QListWidgetItem *item) Signal emitted when an item is double-clicked.
setItemWidget(QListWidgetItem *item, QWidget *widget) Sets the widget at the given item's location.
setIconSize(const QSize &size) Set the size of the project icon.
setCurrentRow(int row) Sets the currently selected row.
setCurrentItem(QListWidgetItem *item) Sets the currently selected item.
selectedItems() Returns all currently selected items.
selectedIndexes() Returns the model index of all items currently selected.
setSelectionMode(QAbstractItemView::SelectionMode mode) Set the selection mode, such as SingleSelectionor MultiSelection.

This is just QListWidgeta subset of the methods of the class. You can check the official documentation for a complete list of methods, as well as detailed descriptions of these methods.

First, readers can draw the UI interface as shown below. The left side of the interface contains a ListWidgetlist box, and the right side contains various buttons for controlling components pushButton, as shown in the figure below;

1.1 Initialize nodes

The following code is a slot function on_pushButton_init_clicked, its main function is to initialize a QListWidgetlist box, which contains a series of QListWidgetItemitems.

Here's an overview:

  1. Clear the list box: First, ui->listWidget->clear()the list box is cleared via to ensure that existing items are removed before initialization.
  2. Loop initialization items: Using forloop, numbers from 0 to 9 were traversed, and a total of 10 items were initialized.
  3. Creation QListWidgetItem: For each loop, new QListWidgetItem()a new QListWidgetItemobject is created via aItem.
  4. Set the text label: Use setTextthe method to QListWidgetItemset the text label, and the content is a string in the form of "192.168.1.x".
  5. Set the icon: Use setIconthe method to set the same icon for each item, here the icon named "1.ico" is used.
  6. Set to selected state: Use setCheckStatethe method to set each item to selected state, that is, display the check box and check it.
  7. Set non-editable state: Use setFlagsthe method to set each item to a non-editable state, allowing only selection and inspection operations.
  8. Add items to the list: Use ui->listWidget->addItem(aItem)to add each item to QListWidget.

This slot function is used to initialize a property containing specific icons, text, check boxes, etc. QListWidgetto facilitate user selection and operation.

// 初始化列表
void MainWindow::on_pushButton_init_clicked()
{
    
    
    // 每一行是一个QListWidgetItem
    QListWidgetItem *aItem;

    // 设置ICON的图标
    QIcon aIcon;
    aIcon.addFile(":/image/1.ico");

    // 清空列表框
    ui->listWidget->clear();

    // 循环初始化
    for(int x=0;x<10;x++)
    {
    
    
        // 填充字符串
        QString str = QString::asprintf("192.168.1.%d",x);

        // 新建一个项
        aItem = new QListWidgetItem();

        aItem->setText(str);                        // 设置文字标签
        aItem->setIcon(aIcon);                      // 设置图标
        aItem->setCheckState(Qt::Checked);          // 设为选中状态
        aItem->setFlags(Qt::ItemIsSelectable |      // 设置为不可编辑状态
                         Qt::ItemIsUserCheckable
                        |Qt::ItemIsEnabled);

        // 增加项到列表中
        ui->listWidget->addItem(aItem);
    }
}

The running effect is as shown below;

1.2 Set editing status

The main function of the following slot function on_pushButton_edit_clickedis to set all items to editable state.

Here's an overview:

  1. Get the number of all items: Use to ui->listWidget->count()get the number of items in the list box.
  2. Loop to set the state: Use forto loop through each item and get the handle of the current item.
  3. Set to editable state: Use setFlagsthe method to set the state of each item to editable, including selectable, editable, checkable, enableable, etc.

The function of this slot function is to set the status of all items in the list box to editable, so that the user can modify the text content of these items at run time.

// 设置所有项设置为可编辑状态
void MainWindow::on_pushButton_edit_clicked()
{
    
    
    int x,cnt;
    QListWidgetItem *aItem;

    // 获取所有项数量
    cnt = ui->listWidget->count();
    for(x=0;x<cnt;x++)
    {
    
    
        // 得到当前选中项句柄
        aItem = ui->listWidget->item(x);

        // 设置状态
        aItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable
                        |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
    }
}

The running effect is as shown below;

1.3 Select all and reverse selection

The core function of the following slot function on_pushButton_selectall_clickedis to implement a select all button, that is, to set all items in the list box to the selected state.

Here's an overview:

  1. Get the total number: Use to ui->listWidget->count()get the total number of items in the list box.
  2. Loop to set the selected state: Use forto loop through each item and get the pointer of each item.
  3. Set to selected state: Use setCheckStatethe method to set the state of each item to the selected state, that is, check the checkbox.

The function of this slot function is to implement a select all button to facilitate the user to select all items in the list box at one time.

void MainWindow::on_pushButton_selectall_clicked()
{
    
    
    // 获取总数
    int cnt = ui->listWidget->count();
    for(int x=0;x<cnt;x++)
    {
    
    
        // 获取到项的指针
        QListWidgetItem *aItem = ui->listWidget->item(x);

        // 设置为选中
        aItem->setCheckState(Qt::Checked);
    }

}

The core function of the following slot function on_pushButton_noselect_clickedis to implement a select-all button, that is, to set all items in the list box to an unselected state.

Here's an overview:

  1. Get the total number: Use to ui->listWidget->count()get the total number of items in the list box.
  2. Loop to set the unselected state: Use forto loop through each item and get the pointer of each item.
  3. Set to unchecked: Use setCheckStatethe method to set the status of each item to unchecked, that is, uncheck the checkbox.

The function of this slot function is to implement a select-all button to facilitate the user to uncheck all items in the list box at once.

void MainWindow::on_pushButton_noselect_clicked()
{
    
    
    // 获取总数
    int cnt = ui->listWidget->count();
    for(int x=0;x<cnt;x++)
    {
    
    
        // 获取到一项指针
        QListWidgetItem *aItem = ui->listWidget->item(x);

        // 设置为非选中
        aItem->setCheckState(Qt::Unchecked);
    }
}

The core function of the following slot function on_pushButton_deselect_clickedis to implement an inverse selection button, which inverts the selected state of each item in the list box.

Here's an overview:

  1. Get the total number: Use to ui->listWidget->count()get the total number of items in the list box.
  2. Loop to set the deselected state: Use forto loop through each item and get the pointer of each item.
  3. Unselected state: Use checkStatethe method to get the current selected state of each item. If it is selected ( Qt::Checked), set it to the unselected state ( Qt::Unchecked), and vice versa.

The function of this slot function is to implement an invert button to facilitate the user to reverse the selected state of all items in the list box at one time.

void MainWindow::on_pushButton_deselect_clicked()
{
    
    
    int x,cnt;
    QListWidgetItem *aItem;

    // 获取总数
    cnt = ui->listWidget->count();
    for(x=0;x<cnt;x++)
    {
    
    
        // 获取到一项指针
        aItem = ui->listWidget->item(x);

        // 如果未选中则选中否则不选
        if(aItem->checkState() != Qt::Checked)
            aItem->setCheckState(Qt::Checked);
        else
            aItem->setCheckState(Qt::Unchecked);
    }
}

The running effect is as shown below;

1.4 Insert and append

The core function of the following slot function on_pushButton_add_clickedis to implement an "Add an item" button, that is, to append a new item to the end of the list box.

Here's an overview:

  1. Create an icon: Use to QIconcreate a new icon, here the icon named "2.ico" is used.
  2. Create new QListWidgetItem: Use to new QListWidgetItem("新增的项目")create a new QListWidgetItemobject and set the text to "New Item".
  3. Setting icon and status: Use setIconthe icon of the setting item. setCheckStateThe selected status of the setting item is selected, and setFlagsthe status of the setting item is selectable, checkable, and enableable.
  4. Append to control: Use ui->listWidget->addItem(aItem)to append the newly created item to the end of the list box.

The function of this slot function is to append a new item to the end of the list box, which contains the specified text, icon, and initial selected state.

void MainWindow::on_pushButton_add_clicked()
{
    
    
    QIcon aIcon;
    aIcon.addFile(":/image/2.ico");

    QListWidgetItem *aItem = new QListWidgetItem("新增的项目");    // 增加项目名
    aItem->setIcon(aIcon);                                       // 设置图标
    aItem->setCheckState(Qt::Checked);                           // 设置为选中
    aItem->setFlags(Qt::ItemIsSelectable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);
    ui->listWidget->addItem(aItem);                              // 增加到控件
}

The core function of the following slot function on_pushButton_ins_clickedis to implement an "Insert an item at a specified position" button, that is, to insert a new item at a specified position in the list box.

Here's an overview:

  1. Create an icon: Use to QIconcreate a new icon, here the icon named "3.ico" is used.
  2. Create new QListWidgetItem: Use to new QListWidgetItem("插入的数据")create a new QListWidgetItemobject and set the text to "Inserted Data".
  3. Setting icon and status: Use setIconthe icon of the setting item. setCheckStateThe selected status of the setting item is selected, and setFlagsthe status of the setting item is selectable, checkable, and enableable.
  4. Insert an item at a specified position: Use to ui->listWidget->insertItem(ui->listWidget->currentRow(), aItem)insert a new item above the current row.

The function of this slot function is to insert a new item at the specified position in the list box, which contains the specified text, icon, and initial selected state.

void MainWindow::on_pushButton_ins_clicked()
{
    
    
    QIcon aIcon;
    aIcon.addFile(":/image/3.ico");

    QListWidgetItem *aItem = new QListWidgetItem("插入的数据");
    aItem->setIcon(aIcon);
    aItem->setCheckState(Qt::Checked);
    aItem->setFlags(Qt::ItemIsSelectable |Qt::ItemIsUserCheckable |Qt::ItemIsEnabled);

    // 在当前行的上方插入一个项
    ui->listWidget->insertItem(ui->listWidget->currentRow(),aItem);
}

The running effect is as shown below;

1.5 Delete a row in the list

The core function of the following slot function on_pushButton_delete_clickedis to implement a "Delete Selected Item" button, that is, to delete the currently selected item in the list box.

Here's an overview:

  1. Get the current row: Use to ui->listWidget->currentRow()get the row index of the currently selected item.
  2. Remove the item from the specified row: Use to ui->listWidget->takeItem(row)remove the item from the specified row. This method returns the pointer of the removed item but does not release the space.
  3. Release space: Use to delete aItemrelease the space of the removed item to ensure that no memory leaks occur.

The function of this slot function is to delete the currently selected item in the list box and release the corresponding memory space.

void MainWindow::on_pushButton_delete_clicked()
{
    
    
    // 获取当前行
    int row = ui->listWidget->currentRow();

    // 移除指定行的项,但不delete
    QListWidgetItem *aItem = ui->listWidget->takeItem(row);

    // 释放空间
    delete aItem;
}

The running effect is as shown below;

1.6 Bind right-click menu

In the previous content, we showed how to MainWindowadd a right-click menu to the main form. In this section, we will ListWidgetadd a right-click menu. When the user ListWidgetright-clicks on any sub-item in the component, this menu will pop up and provide options based on the selection. different functions.

First, we draw two UIinterfaces and Tabseparate them through components. In order to facilitate the demonstration, we need to manually add the content of the list items. The method of adding is to ListWidgetright-click on it and select the Edit Item button. At this time, you can enter the data set into the list line by line. .

QActionIn order to add a menu, we first need to add each of them globally to the program, QActionrepresenting a menu option pointer. Since we plan to add three menu options, we will reserve three global menu pointers here.

#include <QMenuBar>
#include <QMenu>
#include <QToolBar>
#include <iostream>

// 全局下设置增加删除菜单
QAction *NewAction;
QAction *InsertAction;
QAction *DeleteAction;

First, take the right-click menu demonstration as an example. In MainWindowthe main function, first create the top menu and set it as a hidden attribute, and then connect Connecteach submenu with Action. The code is as follows;

MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);

    // ----------------------------------------------------
    // 绘制部分
    // ----------------------------------------------------

    // 使用 customContextMenuRequested 信号则需要设置
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    // 隐藏菜单栏上的右击菜单
    this->setContextMenuPolicy(Qt::NoContextMenu);

    // 创建基础顶部菜单
    QMenuBar *bar = menuBar();
    this->setMenuBar(bar);
    QMenu * fileMenu = bar->addMenu("菜单1");

    // 隐藏顶部菜单栏
    bar->setVisible(false);

    // 添加子菜单
     NewAction = fileMenu->addAction("增加IP地址");
     InsertAction = fileMenu->addAction("插入IP地址");
     DeleteAction = fileMenu->addAction("删除IP地址");

    // 分别设置图标
    NewAction->setIcon(QIcon(":/image/1.ico"));
    InsertAction->setIcon(QIcon(":/image/2.ico"));
    DeleteAction->setIcon(QIcon(":/image/3.ico"));

    // ----------------------------------------------------
    // 绑定槽函数
    // ----------------------------------------------------
    connect(NewAction,&QAction::triggered,this,[=](){
    
    
        std::cout << "new action" << std::endl;
    });

    connect(InsertAction,&QAction::triggered,this,[=](){
    
    
        std::cout << "insert action" << std::endl;
    });

    // 以删除为例,演示如何删除选中行
    connect(DeleteAction,&QAction::triggered,this,[=](){
    
    
        int row = ui->listWidget->currentRow();
        QListWidgetItem *aItem = ui->listWidget->takeItem(row);
        delete aItem;
        std::cout << "delete action" << std::endl;
    });
}

Then, when ListWidgetthe right button is clicked, on_listWidget_customContextMenuRequestedthe slot function is triggered. Within the slot function, we create new QMenua new menu and addActioninsert it into the clicked position through attributes. The code is as follows;

// 当listWidget被右键点击时则触发
void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    
    
    std::cout << "x pos = "<< pos.x() << "y pos = " << pos.y() << std::endl;
    Q_UNUSED(pos);

    // 新建Menu菜单
    QMenu *ptr = new QMenu(this);

    // 添加Actions创建菜单项
    ptr->addAction(NewAction);
    ptr->addAction(InsertAction);
    // 添加一个分割线
    ptr->addSeparator();
    ptr->addAction(DeleteAction);

    // 在鼠标光标位置显示右键快捷菜单
    ptr->exec(QCursor::pos());

    // 手工创建的指针必须手工删除
    delete ptr;
}

After running, the reader can right-click on a specific line, and the menu bar will pop up, as shown in the figure below;

Next, let’s take a look at how to set up the icon group and bind the right-click menu. The binding of the second method is the same as the first. The only difference is just the display settings. The following is the display configuration of the second method. code;

// 第二个ListWidget_使用图标方式展示
ui->listWidget_ico->setViewMode(QListView::IconMode);

// 每一行是一个QListWidgetItem
QListWidgetItem *aItem;

// 设置ICON的图标
QIcon aIcon;
aIcon.addFile(":/image/1.ico");

ui->listWidget_ico->clear();
for(int x=0;x<10;x++)
{
    
    
    QString str = QString::asprintf("admin_%d",x);
    aItem = new QListWidgetItem();           // 新建一个项

    aItem->setText(str);                     // 设置文字标签
    aItem->setIcon(aIcon);                   // 设置图标
    //aItem->setCheckState(Qt::Checked);     // 设为选中状态
    aItem->setFlags(Qt::ItemIsSelectable |   // 设置为不可编辑状态
                     Qt::ItemIsUserCheckable
                    |Qt::ItemIsEnabled);

    ui->listWidget_ico->addItem(aItem);       // 增加项
}

When using it, you only need to bind the menu in the same way, and the running effect is as shown in the figure below;

Guess you like

Origin blog.csdn.net/lyshark_csdn/article/details/135054429