我有一个具有插槽fileNew()
的基本窗口。当我运行我的应用程序,我得到以下错误:
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();
}
SdiWindow需要将Q_OBJECT宏作为其第一行。
class SdiWindow : public QMainWindow
{
Q_OBJECT
public: ....
您还必须在头文件上使用moc。moc工具生成信号和槽框架所需的所有c++代码。
生成的moc代码必须被编译并为链接器所知。为此,我将生成的文件包含在实现文件中,如下所示
#include SdiWindow.h
#include SdiWindow.moc
drescherjm还建议单独编译它。
编辑:在这种情况下,你是从QMainWindow继承的,为了将来的参考,你的类将需要以某种方式从QObject继承,以便能够使用信号/槽框架。