如何在QT中检查QMenu项目

时间:2017-07-10 07:32:40

标签: c++ qt qt4

如何使用QT检查Qmenu项目

QMenu *preferenceMenu = new QMenu();
preferenceMenu  = editMenu->addMenu(tr("&Preferences"));

QMenu *Mode1 = new QMenu();
Mode1  = preferenceMenu->addMenu(tr("&Mode 1"));
Mode1->addAction(new QAction(tr("&Menu1"), this));

QMenu *Mode2 = new QMenu();
Mode2  = preferenceMenu->addMenu(tr("&Mode 2"));
Mode2->addAction(new QAction(tr("&Menu2"), this));
Mode2->addAction(new QAction(tr("&Menu3"), this));

在QAction上我调用了slot" slotActionTriggered(QAction * actionSelected)"

void csTitleBar::slotActionTriggered(QAction* actionSelected)
{
   actionSelected->setChecked(true);
}

如何在所选菜单#中显示小TICK,以便用户可以知道选择了哪个 目前我可以更改为所有菜单#,但我需要在菜单上显示一个小刻度,以便可以轻松识别所选的

1 个答案:

答案 0 :(得分:6)

小例子:

enter image description here

<强> cmainwindow.h

#ifndef CMAINWINDOW_H
#define CMAINWINDOW_H

#include <QMainWindow>
#include <QPointer>

class CMainWindow : public QMainWindow
{
   Q_OBJECT

public:
   CMainWindow(QWidget *parent = 0);
   ~CMainWindow();

private slots:
   void slot_SomethingChecked();

private:
   QPointer<QAction> m_p_Act_Button1 = nullptr;
   QPointer<QAction> m_p_Act_Button2 = nullptr;
};

#endif // CMAINWINDOW_H

<强> cmainwindow.cpp

#include "cmainwindow.h"
#include <QtWidgets>
#include <QDebug>

CMainWindow::CMainWindow(QWidget *parent)
   : QMainWindow(parent)
{
   m_p_Act_Button1 = new QAction("Super Button 1", this);
   m_p_Act_Button1->setCheckable(true);
   m_p_Act_Button1->setChecked(true);
   connect(m_p_Act_Button1, SIGNAL(triggered()), this, SLOT(slot_SomethingChecked()));

   m_p_Act_Button2 = new QAction("Super Button 2", this);
   m_p_Act_Button2->setCheckable(true);
   m_p_Act_Button2->setChecked(true);
   connect(m_p_Act_Button2, SIGNAL(triggered()), this, SLOT(slot_SomethingChecked()));

   QMenu *p_menu = menuBar()->addMenu("My Menu");
   p_menu->addAction(m_p_Act_Button1);
   p_menu->addAction(m_p_Act_Button2);
}

CMainWindow::~CMainWindow() { }

void CMainWindow::slot_SomethingChecked()
{
   if(!m_p_Act_Button1 || !m_p_Act_Button2) {return;}

   qDebug() << "Hi";
   if(m_p_Act_Button1->isChecked())
   {
      qDebug() << "The action 1 is now checked";
   }
   else
   {
      qDebug() << "The action 1 is now unchecked";
   }

   if(m_p_Act_Button2->isChecked())
   {
      qDebug() << "The action 2 is now checked";
   }
   else
   {
      qDebug() << "The action 2 is now unchecked";
   }

}