Qt实现右键菜单

一、实现方法

QWidget提供了虚函数:

virtual void contextMenuEvent(QContextMenuEvent*event);

覆写该函数,即可。

二、Example

创建一个基本的mainwindow项目,
头文件:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
		
	//重实现
    void contextMenuEvent(QContextMenuEvent* event) override;
public slots:
    void hello_world();
private:
    Ui::MainWindow *ui;
};

.cpp文件:

void MainWindow::contextMenuEvent(QContextMenuEvent*event)
{
    QMenu *menu = new QMenu(this);

    auto action_del = new QAction("del",this);
    auto action_copy = new QAction("copy",this);
    auto action_export = new QAction("export",this);

    connect(action_del,&QAction::triggered,this, &MainWindow::hello_world);
    menu->addAction(action_del);
    menu->exec(this->cursor().pos());
}

三、效果

在界面上右键会弹出菜单,点击按钮触发槽函数hello_world();
这里我只添加了一个del的按钮。

QAction构造函数中可以提供图标,实现更好看的菜单。

Qt实现右键菜单_第1张图片

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