Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make QMenu Item checkable in QT

Tags:

c++

qt

qt4

How to give Qmenu item checkable using QT

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

On QAction I called slot "slotActionTriggered(QAction* actionSelected)"

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

How to show small TICK in the selected Menu# so that user can know which is selected Currently I am able to change to all Menu#, but I need to show a small tick on menu so that the selected one can be easly Identified

like image 555
Sijith Avatar asked Jul 10 '17 07:07

Sijith


1 Answers

Small example:

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";
   }

}
like image 105
pablo_worker Avatar answered Nov 06 '22 21:11

pablo_worker