2011-11-24 35 views
1

我有處理QMainWindow的「核心」對象。
Core.h代碼Qt主窗口菜單信號

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

我想主窗口菜單欄中的信號連接到這樣的核心插槽:

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

但它不」工作。我新的C + +和Qt。如何連接這個? 或者,也許有更好的方法來處理其他程序部分的主窗口動作。

UPD 問題解決了。忘記包括QMenuBar

+0

如果你已經解決了你的問題,你應該發佈它作爲答案並接受它。這樣,如果提到診斷錯誤消息,它將使其他人更受益於 – musefan

回答

7

你必須在SIGNAL和SLOT參數(但沒有參數名稱)給出全功能規格。就像這樣:

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

如果您在Qt Creator的調試這樣的代碼,該connect功能會寫診斷錯誤信息發送給應用輸出窗格中,當它沒有找到一個信號或插槽。我建議您在解決問題之前先找到這些錯誤消息,以便將來知道將來的位置。信號和插槽錯誤很容易!

+0

+1。這些真的很有用。我想很多人會忽視他們。 –

+0

我得到QT以下錯誤: '呼叫沒有匹配功能的核心::連接(QMenuBar *,爲const char *,芯* const的,爲const char *)' 候選人是:靜態布爾QObject的: :connect(const QObject *,const char *,const QObject *,const char *,Qt :: ConnectionType)' –

+0

看起來像你從一個聲明爲'const'的成員函數調用'connect'(看'Core *錯誤消息中的const)。是對的嗎? – TonyK