Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c++ - 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 ?

question from:https://stackoverflow.com/questions/65862777/qt-how-to-emit-a-signal-from-derived-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...