Qt creator 创建鼠标右键菜单 (不新建类)

时间:2022-05-24 23:05:54

界面

Qt creator 创建鼠标右键菜单  (不新建类)

步骤

  1. 打开你的界面文件并选中你要添加右键的控件,选择“CustomContextMenu”

    Qt creator 创建鼠标右键菜单  (不新建类)

  2. 右键选择“转到槽...” -> customContextMenuRequested
    Qt creator 创建鼠标右键菜单  (不新建类)
  3. 插入下面代码即可
    void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
    {
    static QMenu *qMenu = NULL;
    if (qMenu == NULL)
    {
    qMenu = new QMenu(ui->listWidget);
    QAction* closePaneAction = new QAction("&Close",this);
    connect(closePaneAction, SIGNAL(triggered()), this, SLOT(close())); qMenu->addAction(closePaneAction);
    } qMenu->exec(QCursor::pos()); //在鼠标点击的位置显示鼠标右键菜单
    }