1

我想创建一个派生自的类QLineEdit,但我无法为 Escape 按钮分配信号。

代码一直有效,直到我添加cancel_signal()然后

LNK2019/LNK1120

出现错误。

如何为 Escape 按钮分配信号?


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;
}
4

1 回答 1

3

您收到此链接错误,因为信号是尚未定义的 C++ 函数。这通常由 完成moc,它不会生成您的类的某些代码。

每当您想在QObject派生类中使用信号和插槽或需要其他使用 的东西时QMetaObject,您需要添加

Q_OBJECT

在类定义的左大括号之后。

请注意,当您添加此宏时,您还需要手动运行 qmake,因为 QtCreator 会尝试智能并在.pro文件未更改的情况下跳过此构建步骤。但是必须将宏的预先或不存在Q_OBJECT视为对 qmake 的更改,因为moc(元对象编译器)需要运行在类定义中具有Q_OBJECT宏的所有文件。

于 2012-06-23T15:06:13.673 回答