QT主窗体右键弹出下拉菜单方法(我的主窗体的类名是CGuiMainwindow):
void CGuiMainwindow::contextMenuEvent(QContextMenuEvent* e)
{
QMenu *menu = new QMenu();
menu->addSeparator();
menu->addSeparator();
menu->addAction(Act_Maxsize);
menu->addSeparator();
menu->addSeparator();
menu->addAction(Act_Normal);
menu->addSeparator();
menu->addSeparator();
menu->exec(e->globalPos());
delete menu;
}
其中Act_Maxsize和Act_Normal是两个QAction 对象指针。我的定义和初始化如下:
QAction* Act_Maxsize;
QAction* Act_Normal;
Act_Maxsize = new QAction(tr("XML"), this);
Act_Maxsize->setIcon(QIcon("Resources/logo.png"));
Act_Normal = new QAction(tr("SHOW"), this);
Act_Normal->setIcon(QIcon("Resources/logo.png"));
connect(Act_Maxsize, SIGNAL(triggered()), this, SLOT(ADDChange()));
connect(Act_Normal, SIGNAL(triggered()), this, SLOT(XMLChange()));
QT内置控件添加右键菜单方法(以QTreeWidget添加右键菜单为例):
connect(moduleTree,SIGNAL(itemPressed(QTreeWidgetItem *, int)),
this,SLOT(SlotItemClicked(QTreeWidgetItem *, int)));
实现槽函数
void CGuiMainwindow::SlotItemClicked(QTreeWidgetItem *item, int column){
if (qApp->mouseButtons() == Qt::LeftButton){return;}
if (qApp->mouseButtons() == Qt::RightButton){if (item->childCount() > 0){return;}ShowMenu();}}
实现菜单显示功能函数:
void CGuiMainwindow::ShowMenu(){
QPoint pos;QMenu menu(moduleTree);QIcon myIcon("Resources/logo.png");menu.addAction(myIcon,tr("菜单_1"));menu.addAction(myIcon,tr("菜单_2"));menu.addAction(myIcon,tr("菜单_3"));menu.addAction(myIcon,tr("菜单_4"));menu.addAction(myIcon,tr("菜单_5"));menu.addAction(myIcon,tr("菜单_6"));menu.exec(QCursor::pos());}