我有一个带有插槽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()
怎么了?
将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;
};