1、实现的效果如下:
2、实现代码
(1)头文件
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QListViewDemo.h"enum ListDataType
{
ldtNone = -1,
ldtOne = 0,
ldtTwo = 1,
};struct ListData
{
QString strImgPath;
ListDataType eListDataType;
QString strText;
};class QListViewDemo : public QMainWindow
{
Q_OBJECTpublic:
QListViewDemo(QWidget *parent = Q_NULLPTR);private:
Ui::QListViewDemoClass ui;
QList<ListData> m_lstData; QMap<QListWidgetItem* , ListDataType> m_mapWidget;
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
(2)实现文件
#include "QListViewDemo.h"
QListViewDemo::QListViewDemo(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this); ui.listWidget->setViewMode(QListView::ViewMode::IconMode);
//ui.listWidget->setIconSize(QSize(80, 80));
ui.listWidget->setResizeMode(QListWidget::Adjust);
//ui.listWidget->setGridSize(QSize(150, 150));
ui.listWidget->setSpacing(5);
ui.listWidget->setMovement(QListWidget::Static); {
ListData _ListData;
_ListData.strImgPath = ":/QListViewDemo/images/1.png";
_ListData.eListDataType = ldtOne;
_ListData.strText = "Sample1";
m_lstData.append(_ListData);
}
{
ListData _ListData;
_ListData.strImgPath = ":/QListViewDemo/images/1.png";
_ListData.eListDataType = ldtTwo;
_ListData.strText = "Sample2";
m_lstData.append(_ListData);
} for (int i = 0; i < m_lstData.size(); i++)
{
QListWidgetItem* imageItem = new QListWidgetItem;
imageItem->setIcon(QIcon(m_lstData.at(i).strImgPath));
imageItem->setSizeHint(QSize(100, 100));
imageItem->setText(m_lstData.at(i).strText);
ui.listWidget->addItem(imageItem); m_mapWidget[imageItem] = m_lstData.at(i).eListDataType;
} connect(ui.listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(_slotitemClicked(QListWidgetItem*)));
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
点击按钮事件
public slots:
void _slotitemClicked(QListWidgetItem* item);
实现函数如下
void QListViewDemo::_slotitemClicked(QListWidgetItem* item)
{
auto itrFind = m_mapWidget.find(item);
if (itrFind != m_mapWidget.end())
{
ListDataType eListDataType = itrFind.value();
switch (eListDataType)
{
case ldtOne:
{
int yyy = 5;
break;
}
case ldtTwo:
{
int yyy = 5;
break;
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.