4

I have the following example in Qt in which I try to override the keyPressEvent of a subclass of QTextEdit, but gives me a "multiple definition of txt::keyPressEvent(QKeyEvent*)" and I can't figure out why:

//txt.h
#ifndef TXT_H
#define TXT_H

#include <QTextEdit>

class txt : public QTextEdit
{
    Q_OBJECT
public:
    txt(QWidget *parent = 0);

signals:
    void keyPressEvent(QKeyEvent *e);

public slots:

};

#endif // TXT_H


//txt.cpp
#include "txt.h"

txt::txt(QWidget *parent) :
    QTextEdit(parent)
{
}

void txt::keyPressEvent(QKeyEvent *e){
    //do stuff with the key event
}


//main.cpp
#include <QtGui/QApplication>
#include "txt.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    txt w;
    w.show();

    return a.exec();
}

I tried forward declaring QTextEdit in txt.h and #including it only in the cpp, but that gives me some other errors (probably because I need the class in the header, since i'm subclassing it?)

Anyway, what am I doing wrong?

EDIT: I also tried it with another class (QLabel), and now I'm getting the same error...

4

1 回答 1

6

The problem is that you declared it as a signal. This should work find :

class txt : public QTextEdit
{
    Q_OBJECT
public:
    txt(QWidget *parent = 0);

protected:
    virtual void keyPressEvent(QKeyEvent *e);

public slots:

};
于 2012-03-21T22:33:12.000 回答