Infinite recursion with Qt-connected signal / slot

I think I have a fundamental misunderstanding of how the Qt signal / slot mechanism works.

I worked on sample programs, and they make sense, but when I tried to take and modify them, I get results that I don’t understand. I have attached the sample code below, which is a low-key version of what I was trying to do, which of course does not do what I want. Am I using the signal / slot mechanism and the QString class incorrectly? Am I using a signal / slot to change things in a connection, creating an infinite loop? Any help was greatly appreciated.

 // test.cpp #include <QApplication> #include <QDialog> #include <QLineEdit> #include <QString> #include <QVBoxLayout> class myDialog : public QDialog { Q_OBJECT public: myDialog() : a_( new QLineEdit ), b_( new QLineEdit ) { QVBoxLayout* layout( new QVBoxLayout( this ) ); layout->addWidget( a_ ); layout->addWidget( b_ ); connect( a_, SIGNAL( textChanged( const QString& ) ), this, SLOT( aChanged( const QString& ) ) ); connect( b_, SIGNAL( textChanged( const QString& ) ), this, SLOT( bChanged( const QString& ) ) ); } private: QLineEdit* a_; QLineEdit* b_; private slots: void aChanged( const QString& qs ); void bChanged( const QString& qs ); }; #include "test.moc" void myDialog::aChanged( const QString& qs ) { b_->setText( QString::number( 2.0 * qs.toDouble() ) ); } void myDialog::bChanged( const QString& qs ) { a_->setText( QString::number( 3.3 * qs.toDouble() ) ); } int main( int argc, char** argv ) { QApplication a( argc, argv ); myDialog d; d.show(); return a.exec(); } 
+4
source share
2 answers

Since you are editing b QLineEdit in aChanged, it calls the textChanged () signal for b ... causing it to call bChanged, change ..... etc. etc.

I think this is your problem.

You can use textEdited () instead .

+3
source

Not so important in this case, but pay attention to removing a_ and b_ in the destructor, since they do not have a parent.

-1
source

Source: https://habr.com/ru/post/1347397/


All Articles