Qt右键菜单

先创建菜单指针:

#include 
QMenu* pMenu = nullptr;
pMenu = new QMenu(this);

设置菜单策略:

this->setContextMenuPolicy(Qt::DefaultContextMenu);

创建动作并将动作添加进菜单,通过槽函数设置应该进行的相关动作:

QAction* pA1 = new QAction(u8"动作一");
	pMenu->addAction(pA1);
	QAction* pA2 = new QAction(u8"动作二");
	pMenu->addAction(pA2);
	QAction* pA3 = new QAction(u8"动作三");
	pMenu->addAction(pA3);
	QAction* pA4 = new QAction(u8"动作四");
	pMenu->addAction(pA4);
	connect(pA1, &QAction::triggered, [=] {
		QMessageBox::information(this, u8"标题",u8"动作一");
	});
	connect(pA2, &QAction::triggered, [=] {
		QMessageBox::information(this, u8"标题", u8"动作二");
	});
	connect(pA3, &QAction::triggered, [=] {
		QMessageBox::information(this, u8"标题", u8"动作三");
	});
	connect(pA4, &QAction::triggered, [=] {
		QMessageBox::information(this, u8"标题", u8"动作四");
	});

重载contextMenuEvent方法:

void contextMenuEvent(QContextMenuEvent* event) override;
void QtWidgetsApplication2::contextMenuEvent(QContextMenuEvent* event)
{
	pMenu->exec(QCursor::pos());
}

你可能感兴趣的:(qt,开发语言)