How to perform action on clicking a QMenu object only?

好久不见. 提交于 2019-12-10 10:23:11

问题


Here's a snapshot of the GUI. I want to perform simple actions solely by clicking on QMenu object Help. This QMenu object does NOT have any submenus.

Can you please advise me how to perform actions when only the QMenu is clicked Here's what I have tried, but I got an empty output.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>
#include <QSignalMapper>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    void createActions();
    QSignalMapper *pSignalMapper;

private slots:
    void help();

};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    createActions();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::createActions()
{
    pSignalMapper = new QSignalMapper(this);
    connect(ui->menuHelp, SIGNAL(triggered(QAction*)), this, SLOT(help()));

}

void MainWindow::help()
{
    qDebug()<<"inside help qdialog";
}

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <ui_mainwindow.h>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Output when I click on Help QMenu, absolutely nothing:

Starting E:\Qt2\modules\guiPrototype2\build-guiPrototype2-Desktop_Qt_5_2_0_MSVC2010_32bit-Debug\debug\guiPrototype2.exe...

回答1:


I would try to do the following:

void MainWindow::createActions()
{
    [..]
    connect(ui->menuHelp, SIGNAL(aboutToShow()), this, SLOT(help()));
}

void MainWindow::help()
{
    qDebug()<<"inside help qdialog";
}



回答2:


The reason it doesn't work, is because you are not triggering any action.

This signal is emitted when an action in a menu belonging to this menubar is triggered as a result of a mouse click; action is the action that caused the signal to be emitted.

What you should do is add an action to your QMenuBar instead of a QMenu.

QAction *helpAction = ui->menuBar->addAction("Help");
connect(helpAction, SIGNAL(triggered()), this, SLOT(help()));


来源:https://stackoverflow.com/questions/22197496/how-to-perform-action-on-clicking-a-qmenu-object-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!