QListWidget(ListMode)
#include "widget.h"
#include <QListWidgetItem>
#include <QAction>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
resize(300,400);
p_ListWidget = new QListWidget(this);
p_ListWidget->setFixedWidth(100);
QListWidgetItem *item1 = new QListWidgetItem(QIcon(":/img/battery.png"),"battery");
QListWidgetItem *item2 = new QListWidgetItem(QIcon(":/img/offline.png"),"offline");
QListWidgetItem *item3 = new QListWidgetItem(QIcon(":/img/online.png"),"online");
QListWidgetItem *item4 = new QListWidgetItem(QIcon(":/img/system.png"),"system");
p_ListWidget->insertItem(0,item1);
p_ListWidget->insertItem(1,item2);
p_ListWidget->insertItem(2,item3);
p_ListWidget->insertItem(3,item4);
initMenu();
p_ListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(p_ListWidget, &QListWidget::customContextMenuRequested, this, &Widget::on_PopupRightMenu);
}
Widget::~Widget()
{
}
void Widget::on_PopupRightMenu(const QPoint &pos)
{
QListWidgetItem * p_item = p_ListWidget->itemAt(pos);
if (!p_item)
{
return;
}
p_Menu->exec(QCursor::pos());
}
//右键菜单
void Widget::initMenu(void)
{
p_Menu = new QMenu(this);
QAction *act1 = new QAction(QIcon(":/img/battery.png"),"测试1");
QAction *act2 = new QAction(QIcon(":/img/offline.png"),"测试2");
QAction *act3 = new QAction(QIcon(":/img/online.png"),"测试3");
QAction *act4 = new QAction(QIcon(":/img/system.png"),"删除");
p_Menu->addAction(act1);
p_Menu->addAction(act2);
p_Menu->addAction(act3);
p_Menu->addAction(act4);
connect(act4, &QAction::triggered, [=]{
QListWidgetItem * p_Item = p_ListWidget->currentItem();
p_ListWidget->removeItemWidget(p_Item);
delete p_Item;
});
}