QT Basics: Traverse QListWidget, and a simple demonstration of QListWidget, suitable for beginners

QListWidget is a list box. For its detailed introduction, please refer to: Qt QListWidget Detailed Explanation

If beginners just want to understand QListWidget in a short time, you can refer to here

1. Open QT, create a widget project, and add QListWidget and a PushButton to the UI (waiting for backup)

You can double-click the QListWidget widget, click + in the lower left corner to add data in it

Select an item of data, click sit down attribute, you can also add an icon

 

 2. In the window, select the QListWidget widget, and the property bar on the right can also set the size of each row of data, icon size and selection mode. The selection mode is usually unselectable, single selection, multiple selection, continuous selection

    

        

 3. Code demonstration, several different ways to manually add QListWidget data, the code here is written in widget.cpp, traverse QListWidget, here create a slot function to traverse, the slot function is bound to the previously added button

#include "widget.h"
#include "ui_widget.h"
#include <QListWidget>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 清除界面原本的数据
    ui->listWidget->clear();
    // 添加新数据的多种方法s
    QListWidgetItem *item1 = new QListWidgetItem("测试数据1-先new,再add");
    ui->listWidget->addItem(item1);
    QListWidgetItem *item2 = new QListWidgetItem;
    item2->setText("测试数据2-insert插入");
    ui->listWidget->insertItem(0,item2);    // 插入位置,item
    new QListWidgetItem("测试数据3-直接new QListWidgetItem",ui->listWidget);
    ui->listWidget->addItem("测试数据4-直接add,写入text");

    // 插入包含图标的数据
    QListWidgetItem *itemicon = new QListWidgetItem;
    itemicon->setIcon(QIcon("C:/Users/patient/Pictures/Saved Pictures/小黄鸡IKUN篮球.jpg"));
    itemicon->setText("包含图标的数据");
    ui->listWidget->addItem(itemicon);

    // 遍历 ListWidget
    // 设置所有数据为可编辑状态
    // 所有事件都激发 编辑 , 双击、选择、选项变化
    ui->listWidget->setEditTriggers(QAbstractItemView::AllEditTriggers);    // 抽象项目视图::所有编辑触发器
    for(int i = 0;i < ui->listWidget->count();i++)
    {
        ui->listWidget->item(i)->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }
}

// 槽函数
void Widget::click()
{
    // 遍历 ListWidget , 打印文本
    for(int i = 0; i < ui->listWidget->count();i++)
    {
        qDebug() << ui->listWidget->item(i)->text();
    }
}

4. Demonstration animation

 

 

 

Guess you like

Origin blog.csdn.net/qq_39085747/article/details/129310916