如何在QT中使QMenu项目可检查 [英] How to make QMenu Item checkable in QT

查看:42
本文介绍了如何在QT中使QMenu项目可检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用QT检查Qmenu项目

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

在QAction上,我将广告位称为"slotActionTriggered(QAction * actionSelected)"

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

推荐答案

小示例:

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

}

这篇关于如何在QT中使QMenu项目可检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆