How to convert a std :: string into a QString?

5

I'm trying to make a simple display my name dialog box. 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-> getNome));

Implementation to return the name:

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

Can someone give me a light?

    
asked by anonymous 18.06.2014 / 00:21

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 setting of Pessoa .

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

As long as, of course, you change the Pessoa::nome to QString too.

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

Then you can use:

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

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

Of course, in this workaround, you'll have to make sure you have a builder overhead that converts from std::string to QString . Something like:

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

I've placed it on GitHub for future reference.

    
18.06.2014 / 01:24
-1

Using the same question I was able 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

}
    
30.09.2017 / 22:34