How to convert a Std::string to a Qstring?

Asked

Viewed 592 times

5

I’m trying to make a simple dialog box display my name. See the code.

 Pessoa *p = new Pessoa("Ronald Araújo", "[email protected]", 23);

 QMessageBox msg;
 msg.setText(QString::fromUtf8(p->getNome()));
 msg.exec();

But the code breaks in the setText() line with the following error:

error: no matching Function for call to 'Qstring::fromUtf8(Std::string)' msg.setText(Qstring::fromUtf8(p->getName));

Remembering that when I put for example msg.setText(Qstring::fromUtf8("Hi world")) the code runs normally.

Implementation to return the name:

string Pessoa::getNome(){   return this->nome; }

Someone can give me a light?

  • Just to confirm, you added the #include <Qstring> ?

2 answers

5


First solution:

 Pessoa *p = new Pessoa("Ronald Araújo", "[email protected]", 23);

 QMessageBox msg;
 msg.setText(QString::fromStdString(p->getNome()));
 msg.exec();

Second solution:

Change the definition of Pessoa.

QString Pessoa::getNome() { return this->nome; }

As long as, of course, the Pessoa::nome for QString also.

Normally an application made for Qt is preferable to use Qt types. Of course there are situations where this is not possible, hence the first solution is the ideal.

Then you can use:

 Pessoa *p = new Pessoa("Ronald Araújo", "[email protected]", 23);

 QMessageBox msg;
 msg.setText(p->getNome());
 msg.exec();

Evidently in this solution, you will have to ensure that you have a builder overload that does the conversion of std::string for QString. Something like:

Pessoa(string nome, string email, int idade) {
    this.nome = nomeQString::fromStdString(nome);
    this.email = nomeQString::fromStdString(email);
    this.idade = idade;
}

I put in the Github for future reference.

  • Perfect! Thank you very much. I used the very first solution. :)

-1

Using the same doubt I managed to solve a string conversion problem.

void MainWindow::on_HashButton_clicked()
{

    QString msg = ui->lineEdit->text();  // msg RECEBE IFNORMAÇÃO DIGITADA EM lineEdit

    /*antes*/
    // ui->label=>setText(s->sha1(msg.toStdstring())); // no matching function 
    //for call


    ui->label->setText(QString::fromStdString(s->sha1(msg.toStdString()))); // mostra resultado do metodo sha1 em label

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.