Bootstrap

QListWidget中添加QListWidgetItem的几种形式

本文介绍QListWidget中添加QListWidgetItem的几种形式:

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

    // 1
    ui->listWidget->addItem(new QListWidgetItem(QIcon(":/new/prefix1/hat.png"), "123"));

    // 2
    addListWidgetItem("123");

    // 3
    custommodel *model = new custommodel(ui->listView);
    ui->listView->setModel(model);

    // 4
    QListWidgetItem *pItem = new QListWidgetItem(ui->listWidget, 0);
    pItem->setSizeHint(QSize(300, 60));
    QSize size = pItem->sizeHint();

    CustomListItemWidget *pCustomListItemWidget = new CustomListItemWidget(ui->listWidget);
    pCustomListItemWidget->setFixedSize(size);
    ui->listWidget->setItemWidget(pItem, pCustomListItemWidget);
}

第一种是直接使用QListWidgetItem,第二种是添加一个widget进去:

void Widget::addListWidgetItem(QString strText)
{
    QListWidgetItem *pItem = new QListWidgetItem(ui->listWidget, 0);
    pItem->setSizeHint(QSize(ui->listWidget->width(), 60));
    QSize size = pItem->sizeHint();

    QWidget *pWidget = new QWidget(ui->listWidget);
    pWidget->setFixedSize(size);

    QLabel *pLabel1 = new QLabel(pWidget);
    pLabel1->setPixmap(QPixmap(":/new/prefix1/hat.png"));
    pLabel1->setScaledContents(true);

    QLabel *pLabel2 = new QLabel(pWidget);
    pLabel2->setText(strText);

    QLabel *pLabel3 = new QLabel(pWidget);
    pLabel3->setText(strText);

    QHBoxLayout *Hboxlayout = new QHBoxLayout(pWidget);
    Hboxlayout->addWidget(pLabel1);
    Hboxlayout->addWidget(pLabel2);
    Hboxlayout->addWidget(pLabel3);

    ui->listWidget->setItemWidget(pItem, pWidget);
}

第三种是使用model

int custommodel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant custommodel::data(const QModelIndex &index, int role) const
{
	//这里不能直接写return QVariant(QString::fromLocal8Bit("关注微信公众号:高二的笔记"));
	//必须加上判断role == Qt::DisplayRole
    if(role == Qt::DisplayRole)
    {
        return QVariant(QString::fromLocal8Bit("关注微信公众号:高二的笔记"));
    }

    return QVariant();
}

QModelIndex custommodel::index(int row, int column, const QModelIndex &parent) const
{
    return createIndex(row, column);
}

QModelIndex custommodel::parent(const QModelIndex &index) const
{
    return QModelIndex();
}

int custommodel::rowCount(const QModelIndex &parent) const
{
    return 3;
}

//This view does not display horizontal or vertical headers; to display a list of items with a horizontal header, use QTreeView instead.
QVariant custommodel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role == Qt::DisplayRole)
    {
     return QVariant("BING");
    }

    return QVariant();
}

第四种实质还是添加widget,不过是使用setItemWidget添加一个自定义的widget
效果图:
在这里插入图片描述

工程源码地址:https://gitee.com/gao-yuelong/qtdemo/tree/master/listwidget

;