Search code examples
qtvariablesparameter-passingsignals-slotsqstring

access variables outside of slot. pass variables between slots. concatenate string variables in QT


New to Qt. Can you help me understand how to concatenate two QStrings from two different Line Edits?

I have a gui with two line edits. a prefix text, and a number text. I would like to combine the prefix and number value into a single string.

//connect the line edit slots to signals
    QObject::connect(ui->prefixLineEdit, SIGNAL(textChanged(QString)),
                             this, SLOT(prefixChanged()));
    QObject::connect(ui->startNumberLineEdit, SIGNAL(textChanged(QString)),
                             this, SLOT(startNumChanged()));

//functions to run when line edit is changed
void MainWindow::prefixChanged(){
    QString prefixText = ui->prefixLineEdit->text();

}
void MainWindow::startNumChanged(){
    QString startNumberText = ui->startNumberLineEdit->text();

    //combine prefix and start number??
    QString combined = (prefixText + startNumberText);
    ui->statusbar->showMessage(combined);

}

I guess the question in general is how do I share variables between slots? I have read about QSignalMapper, potentially making a proxy slot to pass arguments to, and looked at the .args() function for QString. but that's all sort of beyond me right now.

Do I have to make these variables public in order to access them out of the slot function? I thought that was sort of frowned upon?

Any advice would be much appreciated.


Solution

  • You can do like that, just accessing ui where you need:

    void MainWindow::startNumChanged(){
        QString startNumberText = ui->startNumberLineEdit->text();
        QString prefixText = ui->prefixLineEdit->text();
    
        //combine prefix and start number
        QString combined = prefixText + startNumberText;
        ui->statusbar->showMessage(combined);
    }
    

    You can move this code to some function and call it from each slot if you need.

    In more complex cases, you would need private variables of class in header:

    QString startNumberText;
    QString prefixText;