说真话,以前都不是自定义控件上用,一直没问题,然后我自定义了一个绘图的Canvas,继承自QWidget,想添加右键鼠标弹出菜单,于是遇到两个坑爹的错误!为了节省大家时间,直接看错误就好!
无法跟信号槽方法链接
错误信息:
qobject::connect: no such slot xxxx
其中xxx表示方法名称!
原因是自定义的类没有添加 Q_OBJECT,如果有
看看是否添加了对应的方法,跟绑定声明:
connect(markBin, SIGNAL(triggered()), this, SLOT(on_action_marker()));
加上立刻好!才怪!
class MyImageCanvas : public QWidget { Q_OBJECT public: explicit MyImageCanvas(); void resetCanvas(QPixmap &bitmap, std::vector<cv::Rect> &boxes); void refreshView(); protected: void paintEvent(QPaintEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; private slots: void on_action_marker(); private: int shift_x = 0; int shift_y = 0; float aspect_rate = 0.0; QPixmap bitmap; std::vector<cv::Rect> boxes; QString tooltips; int anchor_x = 0; int anchor_y = 0; bool showColor = false; QString colortips; };
然后就编译,得到下面一堆错误:
error LNK2001: unresolved external symbol "public: virtual int
完整类似的如下:
Linking... error LNK2001: unresolved external symbol "public: virtual int __thiscall MyMainWindow::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@MyMainWindow@@UAEHW4Call@QMetaObject@@HPAPAX@Z) error LNK2001: unresolved external symbol "public: virtual void * __thiscall MyMainWindow::qt_metacast(char const *)" (?qt_metacast@MyMainWindow@@UAEPAXPBD@Z) error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall MyMainWindow::metaObject(void)const " (?metaObject@MyMainWindow@@UBEPBUQMetaObject@@XZ) debug/testqt.exe : fatal error LNK1120: 3 unresolved externals Error executing link.exe.
这段是我网上借用的,大致即时这些错误!告诉你只要一招就可以搞定!
QT Creator中【构建】->【清理所有项目】之后
注释Q_OBJECT,再编译,然后放开注释,
重新编译即可!程序运行如下: