关于QListWidget右菜单的的实现,网上多数资料都没有提到如何使用Qt Creator快速实现(如参考资料[1][2]),本文重点介绍此方法。
1 槽函数生成
通过Qt Creator的UI设计器将QListWidget控件拖放到主界面中,然后右键单击QListWidget控件,在弹出的槽选择框中,选中customContextMenuRequested(Point)槽,然后确定:
图1
若想通过右键单击QListWidget触发与customContexMenuRequsted()绑定的信号,还得设置QListWidget的MenuPolicy属性。有2种方法可以达到此目的。
方法一:
选中QListWidget控件,然后在右侧的属性栏中修改contextMenuPolicy属性为CustomContextMenu,如下图所示:
图1.2
方法二:
在构建函数中添加如下设置代码:
ui->seedsListWidget->setContextMenuPolicy( Qt::CustomContextMenu );
说明:(1) seedsListWidget是我对QListWidget控件的名字,实际使用时,根据实际的名字进行修改。
(2) 两种方法,使用其一即可。本文推荐使用方法一。
2 槽函数完善
本文要达到的效果是,为QListWidget控件添加2个右键菜单“Delete”和“Clear”,分别用于删除选中的项和清空QListWidget。
2.1 custumContextMenu槽函数
void SegmentationSetting3D::on_seedsListWidget_customContextMenuRequested(const QPoint &pos) { QListWidgetItem* curItem = ui->seedsListWidget->itemAt( pos ); if( curItem == NULL ) return; QMenu *popMenu = new QMenu( this ); QAction *deleteSeed = new QAction(tr("Delete"), this); QAction *clearSeeds = new QAction(tr("Clear"), this); popMenu->addAction( deleteSeed ); popMenu->addAction( clearSeeds ); connect( deleteSeed, SIGNAL(triggered() ), this, SLOT( deleteSeedSlot()) ); connect( clearSeeds, SIGNAL(triggered() ), this, SLOT( clearSeedsSlot()) ); popMenu->exec( QCursor::pos() ); delete popMenu; delete deleteSeed; delete clearSeeds; }
2.2 deleteSeedSlot()
void SegmentationSetting3D::deleteSeedSlot() { int ch = QMessageBox::warning(NULL, "Warning", "Are you sure to delete seed ?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if ( ch != QMessageBox::Yes ) return; QListWidgetItem * item = ui->seedsListWidget->currentItem(); if( item == NULL ) return; int curIndex = ui->seedsListWidget->row(item); ui->seedsListWidget->takeItem(curIndex); delete item; }2.3 clearSeedsSlot()
void SegmentationSetting3D::clearSeedsSlot() { int ch = QMessageBox::warning(NULL, "Warning", "Are you sure to clear seeds ?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if ( ch != QMessageBox::Yes ) return; QListWidgetItem * item = ui->seedsListWidget->currentItem(); if( item == NULL ) return; ui->seedsListWidget->clear(); }
参考资料
[1]QListWidget中右键单击Item出现菜单
[2]QListWidget的item上实现右键菜单