效果图:
实现步骤:
1- 新建项目,添加一个listWidget控件。
2- 用代码创建一个QHBoxLayout水平布局的容器。
3- 用代码创建控件添加到水平容器中。
4- 用代码创建QWidget控件,把水平容器加入到QWidget中。
5- 用代码创建QListWidgetItem控件,与QWidget控件关联,添加到listWidget控件中。
完整代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QLineEdit"
#include "QListView"
#include "QVBoxLayout"
#include "QHBoxLayout"
#include "QLabel"
#include "QProgressBar"
#include "QPushButton"
#include "QIcon"
#include "QFont"
#include "QListWidgetItem"
#include "QSize"
#include "QString"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
int i=0;
while(i++<12)
{
QWidget *widget=new QWidget(this);
//使用水平布局类
QHBoxLayout *horLayout = new QHBoxLayout();
//主要控件
QLabel *idLabel = new QLabel();
QLabel *textLabel = new QLabel();
QLabel *speedLabel = new QLabel();
QProgressBar *progressbar = new QProgressBar();
QPushButton *giveupButton = new QPushButton();
QLabel *tipLabel1 = new QLabel();
QLabel *tipLabel2 = new QLabel();
QLabel *filesizeLabel = new QLabel();
//设置不同控件的样式
idLabel->setFixedSize(30, 30);
idLabel->setText(QString::number(i));
idLabel->setAlignment(Qt::AlignCenter);
giveupButton->setText(QStringLiteral("取消下载"));
giveupButton->setFixedSize(70, 24);
QFont tempFont(QStringLiteral("宋体"), 9, 0);
textLabel->setText("filename");
textLabel->setFont(tempFont);
textLabel->setFixedHeight(16);
progressbar->setValue(i*10);
progressbar->setFixedHeight(16);
progressbar->setFont(tempFont);
speedLabel->setFixedSize(150,16);
speedLabel->setAlignment(Qt::AlignRight);
speedLabel->setFont(tempFont);
filesizeLabel->setText("0KB/0KB");
filesizeLabel->setFixedWidth(120);
filesizeLabel->setAlignment(Qt::AlignCenter);
tipLabel1->setText(QStringLiteral("下载中"));
tipLabel1->setFixedWidth(80);
tipLabel1->setAlignment(Qt::AlignCenter);
tipLabel2->setFixedSize(28,28);
//设置左侧、顶部、右侧和底部边距
horLayout->setContentsMargins(0, 0, 0, 0);
//表示各个控件之间的上下间距
horLayout->setSpacing(5);
//添加控件到布局器
horLayout->addWidget(idLabel);
horLayout->addWidget(progressbar);
horLayout->addWidget(filesizeLabel);
horLayout->addWidget(tipLabel1);
horLayout->addWidget(tipLabel2);
horLayout->addWidget(giveupButton);
widget->setLayout(horLayout);
//5- 用代码创建QListWidgetItem控件,与QWidget控件关联,添加到listWidget控件中。
QListWidgetItem *item = new QListWidgetItem();
QSize size = item->sizeHint();
item->setSizeHint(QSize(size.width(), 40));
ui->listWidget->addItem(item);
widget->setSizeIncrement(size.width(), 40);
//将item与widget联系
ui->listWidget->setItemWidget(item, widget);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
PS: 后面还有事件实现,列表增删实现。