Air Conditioner
Air Conditioner

Reputation: 123

Saving the content of a QLineEdit object into a string variable (C++)

I've looked around the Qt Documentation, but within my project, I'd like to having most of the non-graphical 'more thinking' part of my program be on a seperate .cpp file. Given that, I was wanting to take the text typed into a QLineEdit object and save it as a string after the user triggers the 'returnPressed' action, but when I type:

void MainWindow::on_lineEdit_returnPressed()

{
    QMessageBox msgBox;
    msgBox.setText("The entry has been modified.");
    msgBox.exec();
    //The line which should save the contents of the QLineEdit box:
    string input = QLineEdit::text();
}

...Into the template provided by the Qt Creator IDE (with all necessary slots hopefully created) The compiler returns

In member function 'void MainWindow::on_lineEdit_returnPressed()'
cannot call member function 'QString...'

... and so on.

How should I rewrite my code to do this correctly?

Upvotes: 0

Views: 14876

Answers (3)

spxrtzy
spxrtzy

Reputation: 37

For Qt6 this is the best solution that I found

string input = ui->lineEdit->text().toStdString();

A more developed answer from 'alagner'

Upvotes: 0

danieltm64
danieltm64

Reputation: 481

  1. You must choose how to store the string. Your main options are: array of chars, std::string from the standard library, and QString from Qt. If you need to use the string in a third party library then you might need to store it in an std::string or an array of chars, but if that's not the case then I suggest that you simply use QString as it is widely used throughout Qt, although you can convert a QString to std::string or array of chars.

  2. You must actually retrieve the text. To do this you must call the text() function on the QLineEdit instance, not on the QLineEdit class itself. All widgets can be accessed through the ui pointer. Open the designer and check the name of the line edit, the default name is lineEdit, so try replacing the line

string input = QLineEdit::text();

with the line

QString input = ui->lineEdit->text();

Upvotes: 3

alagner
alagner

Reputation: 1

How about that:

lineEdit->text().toStdString()

Upvotes: 0

Related Questions