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());
}

注意,是绑定QAction::triggered,绑QAction::trigger是无效的,不要搞混了。

三、效果

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

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

在这里插入图片描述

相关推荐

  1. Sublime text 添加到鼠标菜单,脚本实现

    2023-12-06 02:02:09       60 阅读
  2. 菜单注册表位置

    2023-12-06 02:02:09       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 02:02:09       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 02:02:09       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 02:02:09       82 阅读
  4. Python语言-面向对象

    2023-12-06 02:02:09       91 阅读

热门阅读

  1. multipath

    multipath

    2023-12-06 02:02:09      51 阅读
  2. C#调用win10系统自带软键盘的方法

    2023-12-06 02:02:09       65 阅读
  3. FFMPEG编译安装、简单使用

    2023-12-06 02:02:09       58 阅读
  4. MFC—CTabCtrl 、CListCtrl

    2023-12-06 02:02:09       76 阅读
  5. ubuntu上创建服务启动python脚本

    2023-12-06 02:02:09       58 阅读
  6. git的使用

    2023-12-06 02:02:09       71 阅读