我想创建一个派生自QLineEdit
的类,但我无法为Escape按钮分配信号。
代码一直有效,直到我添加cancel_signal()
然后
LNK2019 / LNK1120
出现错误。
如何为退出按钮分配信号?
LineEditAlphaNum.h:
#ifndef _LINEEDIT_ALPHA_NUM_
#define _LINEEDIT_ALPHA_NUM_
#include <QtGui>
class LineEditAlphaNum : public QLineEdit
{
public:
LineEditAlphaNum(QWidget* parent);
void setPrevNextWidget(QWidget* prev, QWidget* next);
protected:
void keyPressEvent(QKeyEvent *);
private:
void keyLogic(QString& str, int key);
int keyIndex;
int lastKey;
QWidget* m_pPrev;
QWidget* m_pNext;
signals:
void cancel_signal();
};
#endif // _LINEEDIT_ALPHA_NUM_
LineEditAlphaNum.cpp:
#include "LineEditAlphaNum.h"
LineEditAlphaNum::LineEditAlphaNum(QWidget *parent) :
QLineEdit(parent),
keyIndex(0),
lastKey(0)
{
}
void LineEditAlphaNum::keyPressEvent(QKeyEvent *e)
{
QString str = text();
switch( e->key() )
{
case Qt::Key_Escape:
emit cancel_signal();
case Qt::Key_Up:
m_pPrev->setFocus(Qt::OtherFocusReason);
break;
case Qt::Key_Down:
m_pNext->setFocus(Qt::OtherFocusReason);
break;
case Qt::Key_Right:
keyIndex = 0;
lastKey = e->key();
break;
case Qt::Key_0:
case Qt::Key_1:
case Qt::Key_2:
case Qt::Key_3:
case Qt::Key_4:
case Qt::Key_5:
case Qt::Key_6:
case Qt::Key_7:
case Qt::Key_8:
case Qt::Key_9:
keyLogic(str, e->key());
break;
case Qt::Key_Backspace:
str.remove(str.size()-1, 1);
break;
default:
break;
}
setText(str);
}
void LineEditAlphaNum::keyLogic(QString& str, int key)
{
char* Keys[] = {"0 ",
"1",
"2ABC",
"3DEF",
"4GHI",
"5JKL",
"6MNO",
"7PQRS",
"8TUV",
"9WXYZ"};
char* keymap = Keys[ key - Qt::Key_0 ];
int length = strlen(keymap);
if ( lastKey == key )
{
keyIndex = (++keyIndex) % length;
str.remove( str.size()-1, 1 );
}
else
{
keyIndex = 0;
lastKey = key;
}
str.append( QChar( keymap[keyIndex] ) );
}
void LineEditAlphaNum::setPrevNextWidget(QWidget* prev, QWidget* next)
{
m_pPrev = prev;
m_pNext = next;
}
答案 0 :(得分:3)
您遇到此链接错误,因为信号是C ++函数,尚未定义。这通常由moc
完成,它不会生成您班级的某些代码。
每当您想在QObject
派生类中使用信号和插槽或需要使用QMetaObject
的其他内容时,您需要添加
Q_OBJECT
在你的类定义开始花括号后。
请注意,当您添加此宏时,您还需要手动运行qmake ,因为QtCreator会尝试智能并在.pro
文件未更改时跳过此构建步骤。但是Q_OBJECT
宏的预先存在或不存在必须被视为qmake的变化,因为moc
(元对象编译器)需要在具有Q_OBJECT
宏的所有文件上运行在课程定义中。