Ultra newbie Signal Slot question



  • Hi,

    Done lots of RTFM, but would hugely appreciate a tiny bit of starter code which would help me get my head around signals and slots.

    I have a QString variable in my app class, and an LineEdit widget in the ui. Call these myString and myLineEdit.

    I'd like to set up a two-way link as follows: if the user edits the string in the UI, myString should be updated accordingly. Likewise, I'd like a function, e.g. SetString(QString newString) which can be called by other code - updating myString and updating the displayed text in myLineEdit.

    The first part I can handle I think, the second part presumably means I have to get 'SetString' to emit a signal which needs to be connected to a slot of myLineEdit. (?)

    Struggling somewhat to work out both syntax and best-practice - any advice most welcome, thanks in advance.


  • Moderators

    @
    class MyClass : public QWidget
    {
    Q_OBJECT
    // ...
    public slots:
    void setString(const QString &newString);
    QString getString() const;

    signals:
    // optional:
    myStringChanged(const QString &newString);

    protected:
    QString myString;
    }

    // Now, .cpp file:
    MyClass::MyClass(QWidget *parent) : QWidget(parent)
    {
    connect(myLineEdit, SIGNAL(textChanged(QString)), this, SLOT(setString(QString));
    }

    MyClass::setString(const QString &string)
    {
    myString = string;

    if (myLineEdit.text() != string) {
    myLineEdit.blockSignals(true);
    myLineEdit.setText(string);
    myLineEdit.blockSignals(false);
    }
    }
    @

    This should do all you wanted to be done :) This is of course only one of many ways to do the job.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.