【问题标题】:Can't use QString in a QLineEdit nor QComboBox as a parameter不能在 QLineEdit 或 QComboBox 中使用 QString 作为参数
【发布时间】:2014-01-23 22:53:27
【问题描述】:

我正在尝试创建一个函数,当用户想要使用 QPushButton 将名称恢复为默认值时替换 QLineEdit 中的文本。

这是“保存”代码的地方。

`//Must get information in the DB
lineditPlayerName = new QLineEdit("Nouveau Profil");
nameAsDefault = new QString(lineditPlayerName->text());
languageAsDefault = new QString(comboBoxlanguage->currentText());`

这是我用来将值更改回默认值的函数

//This code works
void ProfileManager::revertName(){
    lineditPlayerName->setText("nameAsDefault");
    btnRevertName->setEnabled(false);
}

但我需要这样:

//This code does'nt
void ProfileManager::revertName(){
    lineditPlayerName->setText(NameAsDefault);
    btnRevertName->setEnabled(false);
}

我无法让它工作它给了我这个错误: 调用 'QLineEdit::setText(QString*&)' 没有匹配的函数

谢谢

【问题讨论】:

  • 你真的需要动态分配你的QString吗?在 Qt 中,我几乎不需要这样做。
  • 我已经在线阅读了一个教程,这就是我所拥有的所有形式......如果你能解释为什么我不需要这样做,我将不胜感激,你能解释一下如何去做。
  • 你想要一个 QString nameAsDefault 类的成员,而不是 QString * nameAsDefault(指向字符串的指针)。然后,您只需编写 nameAsDefault = lineeditPlayerName->text() 即可设置它。

标签: c++ qt qstring qcombobox qlineedit


【解决方案1】:

您必须取消引用 NameAsDefault 变量

void ProfileManager::revertName(){
    lineditPlayerName->setText(*NameAsDefault); 
                            // ^ Here I dereferenced the pointer
    btnRevertName->setEnabled(false);
}

nameAsDefault 的类型是 指针 指向 QString。但是 QLineEdit::setText 需要 QString 对象,而不是指针。因此编译器会告诉你没有需要指针的函数。

我没有看到你对nameAsDefault 变量的声明,但是因为

nameAsDefault = new QString(lineditPlayerName->text());

编译,new 返回一个指针,我想它是一个指针。

另外,可能更重要的是,您几乎不应该使用new 分配对象。尤其是来自 Qt 库的对象,它们是隐式共享的。

【讨论】:

  • 你能解释一下为什么,我只需要明白。顺便说一句,感谢您的回答。
  • 感谢您的快速回答,非常感谢。
猜你喜欢
  • 2017-11-17
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多