Qt Mainwindow菜单信号

时间:2011-11-24 08:15:02

标签: qt connect signals-slots slot

我处理QMainWindow的“核心”对象 Core.h代码

class Core : public QObject
{
    Q_OBJECT
public:
    explicit Core(QObject *parent = 0);
    ~Core();
    void appInit();
    int getAuth();

public slots:
    void appExit();

private slots:
    void appMenuTriggered(QAction *action);

private:
    void preInit();
    MainWindow *mwnd;
};

Core.cpp代码

Core::Core(QObject *parent) : QObject(parent)
{
    qDebug() << "Core::Constructor called";
    preInit();
}

Core::~Core()
{
    delete mwnd;
    qDebug() << "Core::Destructor called";
}

int Core::getAuth()
{
    LoginDialog *login = new LoginDialog();
    int r = login->exec();
    delete login;
    return r;
}

void Core::appExit() // connected to qapplication aboutToQuit
{
    qDebug() << "Core::appExit called";
}

void Core::preInit()  // called after getAuth im main.cpp
{
    qDebug() << "Core::preInit called";
}

void Core::appMenuTriggered( QAction *action )
{
    qDebug() << "action triggered";
}

void Core::appInit()
{
    mwnd = new MainWindow();
    mwnd->show();
    qDebug() << "Core::appInit called";
}

我正在尝试将mainwindow菜单信号连接到核心插槽,如下所示:

connect(mwnd->menuBar(), SIGNAL(triggered()), this, SLOT(appMenuTriggered()));

但它不起作用。我是c ++和Qt的新手。怎么连接这个? 或者也许有更好的方法来处理主窗口动作到其他程序部分。

UPD   问题解决了。忘记包括QMenuBar

1 个答案:

答案 0 :(得分:7)

您必须在SIGNAL和SLOT参数中提供完整的函数规范(但不包含参数名称)。像这样:

connect(mwnd->menuBar(),
        SIGNAL(triggered(QAction*)),
        this,
        SLOT(appMenuTriggered(QAction*)));

如果在Qt Creator中调试此类代码,connect函数会在找不到信号或插槽时将诊断错误消息写入“应用程序输出”窗格。我建议您在修复问题之前找到这些错误消息,以便知道将来在哪里查看。信号和插槽很容易出错!