无法在QT中连接插槽

时间:2015-12-08 14:01:15

标签: c++ qt signals-slots slot

我有一个包含广告位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;
}

在mainwidnow.cpp文件中,我意识到这个插槽。我还在.cpp文件中包含.h文件:

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();
    }
}

我已成功编译。但是当我尝试运行程序时,我有这个错误

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

有什么问题?

1 个答案:

答案 0 :(得分:0)

Q_OBJECT宏添加到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;
};