【发布时间】:2015-12-08 14:01:15
【问题描述】:
我有一个带有插槽的主窗口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()
有什么问题?
【问题讨论】:
-
您忘记在 MainWindow 声明中声明 Q_OBJECT。
-
@MohamadElghawi 添加 Q_OBJECT 时,出现编译错误:未定义对 `vtable for MainWindow' 的引用
-
确保重新运行元对象编译器以生成适当的代码。还要确保你在类的私有部分定义了 Q_OBJECT。
-
@MohamadElghawi 谢谢,它有效
标签: c++ qt signals-slots slot