1

I have a main window with slots mainwindow.h

class MainWindow : public QMainWindow
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};
MainWindow::MainWindow()
{
    openAction = new QAction("&Open", this);
    exitAction = new QAction("E&xit", this);

    connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
    connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    fileMenu = menuBar()->addMenu("&File");
    fileMenu->addAction(openAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    textEdit = new QTextEdit;
}

In the mainwidnow.cpp file I realize this slot. Also I include .h filee in the .cpp file:

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
                                                tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        textEdit->setText(in.readAll());
        file.close();
    }
}

I have successfully compiled. But when I try to run program, I have this error

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

What is the problem?

koch_kir
  • 163
  • 17

1 Answers1

2

Add the Q_OBJECT macro to MainWindow:

class MainWindow : public QMainWindow 
{
    Q_OBJECT
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};
BobMorane
  • 3,870
  • 3
  • 20
  • 42