Saving the content of a QLineEdit object into a st

2019-06-14 14:10发布

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?

标签: c++ qt5 c++14
2条回答
Ridiculous、
2楼-- · 2019-06-14 14:50
  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();

查看更多
够拽才男人
3楼-- · 2019-06-14 14:58

How about that:

lineEdit->text().toStdString()
查看更多
登录 后发表回答