如何仅对单击QMenu对象执行操作?

时间:2014-03-05 12:15:22

标签: qt signals-slots qmenu qaction

这是GUI的快照。我想通过单击QMenu对象帮助来执行简单的操作。此QMenu对象没有任何子菜单。Perform action when Help menu is clicked

如果仅点击QMenu,请告诉我如何执行操作 这是我尝试过的,但我得到了一个空的输出。

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

单击帮助QMenu时的输出,绝对没有:

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

2 个答案:

答案 0 :(得分:6)

我会尝试执行以下操作:

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

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

答案 1 :(得分:5)

它不起作用的原因是因为你没有触发任何动作。

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.

您应该做的是向QMenuBar而不是QMenu添加操作。

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