2014-06-13 53 views
0

我有一個基本窗口,有一個插槽fileNew()。當我運行我的應用程序時,出現以下錯誤:Qt找不到插槽

QObject::connect: No such slot QMainWindow::fileNew()

爲什麼找不到插槽?

SdiWindow.h

class SdiWindow : public QMainWindow 
{ 
public: 
    SdiWindow(QWidget * parent = 0); 

private slots: 
    void fileNew(); 

private: 
    QTextEdit * docWidget; 
    QAction * newAction; 

    void createActions(); 
    void createMenus(); 
}; 

SdiWindow.cpp

SdiWindow::SdiWindow(QWidget * parent) : QMainWindow(parent) 
{ 
    setAttribute(Qt::WA_DeleteOnClose); 
    setWindowTitle(QString("%1[*] - %2").arg("unnamed").arg("SDI")); 

    docWidget = new QTextEdit(this); 
    setCentralWidget(docWidget); 

    connect(
    docWidget->document(), SIGNAL(modificationChanged(bool)), 
    this, SLOT(setWindowModified(bool)) 
); 

    createActions(); 
    createMenus(); 
    statusBar()->showMessage("Done"); 
} 

void SdiWindow::createActions() 
{ 
    newAction = new QAction(QIcon(":/images/new.png"), tr("&New"), this); 
    newAction->setShortcut(tr("Ctrl+N")); 
    newAction->setStatusTip(tr("Create a new document")); 
    connect(newAction, SIGNAL(triggered()), this, SLOT(fileNew())); 
} 

void SdiWindow::createMenus() 
{ 
    QMenu * menu = menuBar()->addMenu(tr("&File")); 
    menu->addAction(newAction); 
} 

void SdiWindow::fileNew() 
{ 
    (new SdiWindow())->show(); 
} 

回答

2

SdiWindow需要有Q_OBJECT宏作爲其第一行。

class SdiWindow : public QMainWindow 
{ 
Q_OBJECT 
public: .... 

你也必須在頭文件使用MOCmoc工具爲信號和插槽框架生成所有必需的C++代碼。

生成的moc代碼必須編譯並且鏈接器已知。我通過在我的實現文件生成的文件中像這樣

#include SdiWindow.h 
#include SdiWindow.moc 

drescherjm還建議只是編譯它自身的做到這一點。

編輯:在這種情況下,你從QMainWindow繼承,爲了將來的參考,你的類將需要以某種方式繼承QObject,以便能夠使用信號/插槽框架。

+2

包含的.moc並不一定需要。對我來說,我有moc_classname.cxx。這些是項目的來源。 – drescherjm

+0

@drescherjm當我沒有收錄它時,我遇到了問題。雖然有可能我只是在調用moc生成的東西時忘記這麼做...... – Boumbles

+0

@drescherjm我只是試着評論它,我得到鏈接器錯誤。我相信你的moc代碼只需要被編譯,以便它可以被鏈接。無論這是在您的實施文件或單獨。 – Boumbles