【qt】左键菜单

qt 左键菜单

假设类是EditWinEdow

构造函数里,打开对应区域MenuPolicy

`ui->labMap->setContextMenuPolicy(Qt::CustomContextMenu);

在需要的地方连接信号槽

connect(ui->labMap, SIGNAL(customContextMenuRequested(const QPoint)), this, SLOT(onRightClickMenuRequested()));

EditWinEdow.h中添加

enum RightClickTask{
   TASK_CHANGEVIEW = 1,
   TASK_SYSTEMSET = 2,
   TASK_PARAMSET = 3,
   TASK_DEVLIST = 4,
   TASK_ALARMRECORD = 5,
   TASK_MIN = 6,
   TASK_RESET = 7,
   TASK_EXIT = 8,
   TASK_DEVOPERATE = 9,
   TASK_ADD = 10

};

EditWinEdow.cpp添加对应函数,EditWinEdow.h中添加定义(这个略)

void EditWindow::onRightClickMenuRequested()
{
   std::unique_ptr<QMenu> pMenu(new QMenu(this));
   std::unique_ptr<QAction> pAddDevice(new QAction(tr("新建"), this));
   std::unique_ptr<QAction> pMinTask(new QAction(tr("最小化"), this));
   std::unique_ptr<QAction> pExitTask(new QAction(tr("退出"), this));

   pAddDevice->setData(RightClickTask::TASK_ADD);
   pMinTask->setData(RightClickTask::TASK_MIN);
   pExitTask->setData(RightClickTask::TASK_EXIT);

   pMenu->addAction(pAddDevice.get());
   pMenu->addAction(pMinTask.get());
   pMenu->addAction(pExitTask.get());
   connect(pAddDevice.get(), SIGNAL(triggered()), SLOT(onRightClickMenuEvent()));
   connect(pExitTask.get(), SIGNAL(triggered()), SLOT(onRightClickMenuEvent()));
   connect(pMinTask.get(), SIGNAL(triggered()), SLOT(onRightClickMenuEvent()));
   pMenu->exec(cursor().pos());
}
void EditWindow::onRightClickMenuEvent()
{
   QAction *pEven = qobject_cast<QAction *>(this->sender());//this->sender()就是发信号者 QAction
   //获取发送信息类型 1:添加 2:最小化 3:退出
   int iType = pEven->data().toInt();

   switch (iType)
  {
   case RightClickTask::TASK_ADD:
       mapAddDevice();
       break;
   case RightClickTask::TASK_MIN:
       WindowMin();
       break;
   case RightClickTask::TASK_EXIT:
       Exit();
       break;
   default:
       break;
  }
}
void EditWindow::mapAddDevice()
{
   //略
}

void EditWindow::WindowMin()
{
   this->showMinimized();
}

void EditWindow::Exit()
{
   this->close();
}



posted @ 2021-02-04 14:52  carrotmvp  阅读(375)  评论(0编辑  收藏  举报