【问题标题】:Saving the content of a QLineEdit object into a string variable (C++)将 QLineEdit 对象的内容保存到字符串变量中 (C++)
【发布时间】:2014-09-20 22:34:10
【问题描述】:

我查看了 Qt 文档,但在我的项目中,我希望我的程序的大部分非图形“更多思考”部分位于单独的 .cpp 文件中。 鉴于此,我想在用户触发“returnPressed”操作后将输入到 QLineEdit 对象中的文本保存为字符串,但是当我输入时:

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();
}

...进入 Qt Creator IDE 提供的模板(希望创建所有必要的插槽)编译器返回

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

...等等。

我应该如何重写我的代码才能正确地做到这一点?

【问题讨论】:

    标签: c++ qt5 c++14


    【解决方案1】:
    1. 您必须选择如何存储字符串。您的主要选择是:chars 的数组、标准库中的 std::string 和 Qt 中的 QString。如果您需要在第三方库中使用该字符串,那么您可能需要将其存储在 std::string 或 chars 的数组中,但如果不是这种情况,那么我建议您简单地使用 QString在整个 Qt 中被广泛使用,尽管您可以将 QString 转换为 std::string 或 chars 的数组。

    2. 您必须实际检索文本。为此,您必须在 QLineEdit 实例上调用 text() 函数,而不是在 QLineEdit 类本身上。所有小部件都可以通过ui 指针访问。打开设计器查看行编辑的名称,默认名称为lineEdit,所以换行试试

    string input = QLineEdit::text();

    用线

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

    【讨论】:

    • 您的方法效果很好,但我应该如何将 QString 类型转换为 std::string?
    • 稍有改动:std::string input = ui->lineEdit->text().toStdString();
    • 我输入了杜比的想法,但现在创作者给了我一个“从‘QString’转换为非标准类型‘std::string’请求’的错误。现在可能出了什么问题?
    • 我不知道为什么,但我不得不使用ui.lineEdit 而不是ui->。
    【解决方案2】:

    怎么样:

    lineEdit->text().toStdString()
    

    【讨论】:

    • 如果您能详细说明为什么这是正确的以及为什么提问者的代码不起作用,那就太好了。
    猜你喜欢
    • 2012-04-04
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2019-08-19
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    相关资源
    最近更新 更多