对函数发送的未定义引用
undefined reference to function send
我是C++/Qt编程的新手。我制作了这个简单的对话框来检查 QLineEdit,如果输入的文本是"bob",则应启用"确定"按钮。我无法让它成功编译,它给了我:
dialog.cpp|31|undefined reference to `Dialogmio::send()'
我做错了什么?
这是dialog.h:
//dialog.h
#ifndef DIALOG_H_INCLUDED
#define DIALOG_H_INCLUDED
#include <QDialog>
class QPushButton;
class QLineEdit;
class Dialogmio : public QWidget
{
public:
Dialogmio(QWidget *parent =0);
signals:
void send ();
public slots:
void recip(QString &text);
private:
QLineEdit *linedit;
QPushButton *buttonOK;
};
#endif
这是对话框.cpp:
//dialog.cpp
#include <QtGui>
#include "dialog.h"
Dialogmio::Dialogmio(QWidget *parent)
: QWidget(parent)
{
linedit = new QLineEdit();
buttonOK = new QPushButton("OK");
buttonOK->setEnabled(FALSE);
connect( linedit, SIGNAL( textChanged(const QString &) ), this, SLOT( recip(const QString &) ));
connect (this,SIGNAL( send()), this, SLOT( buttonOK->setEnabled(true)) );
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(linedit);
layout->addWidget(buttonOK);
setLayout(layout);
}
void Dialogmio::recip(QString &text)
{
QString a = linedit->text();
if (a == "bob"){
emit send(); //here it gives me the error
}
}
这是主要的.cpp:
#include <QApplication>
#include "dialog.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Dialogmio *dialog = new Dialogmio;
dialog->show();
return app.exec();
}
我已经按照建议插入了Q_OBJECT
宏,现在我在第 7 行又出现了一个错误:
dialog.cpp|7|undefined reference to `vtable for Dialogmio'|
你首先包括QDialog的Qt文件,但随后继续从QWidget继承。虽然从QWidget继承不是问题,但你打算实际从QDialog(?)继承,在这种情况下,你应该这样定义你的类:-
class Dialogmio : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget* parent);
private slots:
void aSlotFunction();
}
信号和插槽机制是Qt独有的C++扩展,为了使类使用它,该类必须包含Q_OBJECT宏,这增加了所有必要的功能。在构建阶段,Qt解析标头并创建扩展所需的代码,包括运行时类型信息,动态属性系统,当然还有信号和插槽。
正如您声明使用代码块作为 IDE 时,如果它在构建之前没有自动运行 qmake,则每当向类添加任何信号或插槽以使 moc(元对象编译器)看到它们时,都需要执行此操作。
另一件事是连接信号和插槽的调用是错误的:-
connect (this,SIGNAL( send()), this, SLOT( buttonOK->setEnabled(true)) );
SLOT 宏中的参数采用插槽功能,因此您需要创建一个插槽并将其连接到发送信号:-
connect(this, SIGNAL(send()), this, SLOT(aSlotFunction());
在aSlotFunction中,您可以调用为按钮启用的集合:-
void Dialogmio::aSlotFunction()
{
buttonOK->setEnabled(true);
}
如果您使用的是Qt 5,则处理连接的语法更简单:-
connect(this, &Dialogmio::send, this, &Dialogmio::aSlotFunction);
由于此语法接受指向将要调用的函数的指针,因此实际上不必将它们声明为槽才能工作。此外,您不提供参数,因此如果它们发生更改,您也不必更新连接调用。
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用