Search code examples
c++qtsignals-slotsderived-class

Qt - how to emit a signal from derived class?


In my custom derived class I'm trying to add and emit a signal gotChange(QString change):

#ifndef NETTEXTEDITOR_H
#define NETTEXTEDITOR_H

#include <QTextEdit>

class NetTextEditor : public QTextEdit {
    using QTextEdit::QTextEdit;
public:
    void keyPressEvent(QKeyEvent *e) override;

signals:
    void gotChange(QString change);
};

#endif // NETTEXTEDITOR_H

Declaration is ok, but when I try to emit it, I get the next error:

/home/mrsydar/Projects/Qt/DOCSHARE/nettexteditor.cpp:5: error:
‘gotChange’ was not declared in this scope
../DOCSHARE/nettexteditor.cpp: In function ‘void doEmit(QString)’:
../DOCSHARE/nettexteditor.cpp:5:10: error: ‘gotChange’ was not
declared in this scope
5 | emit gotChange(em);
| ^~~~~~~~~

I think that it is because of derivation, but I'm very new to Qt and don't know any alternatives or how to fix this.

#include "nettexteditor.h"
#include <QKeyEvent>

void NetTextEditor::keyPressEvent(QKeyEvent *e) {
    int key = e->key();
     if((key >= 65 && key <= 90) || (key >= 48 && key <= 57)){
         QString delta;
         int position = this->textCursor().position();

         delta = "c " + QString::number(position) + " " + (char) key;

         emit gotChange(delta);   //if i comment this emit out, everything compiles without errors
     }
}

What am I doing wrong ?


Solution

  • If you want to create signals or slots then you must use the macro Q_OBJECT in the private section. Then you can run "run qmake" (or simply delete the build folder) and compile the application