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_OBJECT
public:
QListViewDemo(QWidget *parent = Q_NULLPTR);
private:
Ui::QListViewDemoClass ui;
QList<ListData> m_lstData;
QMap<QListWidgetItem* , ListDataType> m_mapWidget;
};
(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*)));
}
点击按钮事件
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;
}
}
}
}
源代码如下:
https://download.csdn.net/download/u011269801/89521670?spm=1001.2014.3001.5503