- 右键弹出菜单:
重写void QWidget::contextMenuEvent(QContextMenuEvent)函数
如:void MainWindow::contextMenuEvent( QContextMenuEvent* e)
{
QMenu *menu = new QMenu();
menu->addAction(openAct);
menu->addSeparator();
menu->addAction(quitAct);
menu->exec(e->globalPos());
delete menu;
} - 定制原生器件的弹出菜单(某些器件可能本身就自带popMenu)
那么如何获得已有的菜单项呢?利用:QList<QAction *> QWidget::actions() const
返回的是其所包含QAction的一个列表。
如:TextViewer::TextViewer() : QTextEdit()
{
this->setReadOnly(true);
}
void TextViewer::contextMenuEvent ( QContextMenuEvent* e )
{
QMenu *menu = createStandardContextMenu();
// remove the separator between 'copy' & 'select all'
menu->removeAction(menu->actions().at(1));
// insert separator before 'copy'
QAction *sepTop = menu->insertSeparator(menu->actions().at(0));
// insert 'open' & 'top' before that separator
menu->insertAction(sepTop, ((MainWindow*)this->parentWidget())->openAction());
menu->insertAction(sepTop, ((MainWindow*)this->parentWidget())->topmostAction());
// add separator after 'select all'
menu->addSeparator();
// add 'quit' after that separator
menu->addAction(((MainWindow*)this->parentWidget())->quitAction());
menu->exec(e->globalPos());
delete menu;
}
效果预览:
//EOF Read More...