Qt添加右鍵菜單

在*.h添加頭文件

#include <QContextMenuEvent>

定義私有函數

void contextMenuEvent(QContextMenuEvent *e);

定義Action

	QAction *showpoint;
	QAction *showline;
	QAction *showtriangle;


定義槽函數

	void DrawPoint();
	void DrawLine();
        void DrawTriangle();

在*.cpp文件中創建Action

	showpoint = new QAction(codec->toUnicode("點"), this);
	showpoint->setIcon(QIcon(":/GLWIDGET/Resources/point.png"));
	showpoint->setStatusTip(codec->toUnicode("以點顯示"));
	connect(showpoint, SIGNAL(triggered()), this, SLOT(DrawPoint()));

	showline = new QAction(codec->toUnicode("線"), this);
	showline->setIcon(QIcon(":/GLWIDGET/Resources/line.png"));
	showline->setStatusTip(codec->toUnicode("以線顯示"));
	connect(showline, SIGNAL(triggered()), this, SLOT(DrawLine()));

	showtriangle = new QAction(codec->toUnicode("面"), this);
	showtriangle->setIcon(QIcon(":/GLWIDGET/Resources/triangle.png"));
	showtriangle->setStatusTip(codec->toUnicode("以面顯示"));
	connect(showtriangle, SIGNAL(triggered()), this, SLOT(DrawTriangle()));


創建右鍵菜單響應函數

void GLWIDGET::contextMenuEvent(QContextMenuEvent *e)
{
	QMenu *menu = new QMenu();

	menu->setFixedWidth(100);

	menu->addAction(showpoint);
	menu->addAction(showline);
	menu->addAction(showtriangle);
        menu->exec(e->globalPos());
	delete menu;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章