qt5-入门-QListWidget-通过右键快捷菜单复制item内容
#include <QMenu>
#include <QClipboard>
QListWidget* myListWidget = new QListWidget;
// 填充数据
for(int i = 0; i < 5; i++) {
myListWidget->addItem(new QListWidgetItem(QString::number(i)));
}
// 默认是strongfocus,聚焦状态下该元素看起来是空白的
myListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus);
// 设置右键菜单
myListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(myListWidget, &QListWidget::customContextMenuRequested, [&]() {
QMenu menu;
// 复制动作
QAction* copyAction = menu.addAction("Copy");
// 处理
QObject::connect(copyAction, &QAction::triggered, [&]() {
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(myListWidget->currentItem()->text());
});
// 可以添加其他菜单
menu.exec(QCursor::pos());
});
// 设置分隔线
myListWidget->setStyleSheet("QListWidget::item { border-bottom: 1px solid black; }");
myListWidget->setWordWrap(true);
myListWidget->show();