1

So I made a program that simply makes "random" sentences. It chooses a noun and a color adjective from a list of 7 based to a seed that uses ctime. Now I'm trying to convert it into a console app. My issue is that I'm not able to display it correctly. Instead of cout I need to get it all on one label.

error: no matching function for call to 'QLabel::setText(std::string&)'

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <cstdlib>
#include <iostream>
#include <ctime>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_newSentence_clicked()
{
    std::string noun[7] = {"cow", "tree", "marker", "cereal", "calendar", "rug", "hammer"};
    std::string color[7] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};

    srand(time(0));
    int nounRandomizer = (rand()%5);
    int colorRandomizer = ((rand()+1)%5);

    std::string sentence = "The"+noun[nounRandomizer]+" is "+color[colorRandomizer]+".";

    ui->sentenceDisplay->setText(sentence);
}
3
  • I want to clear the error and get it to display in the label. In case it's unclear the string isn't working. Commented Jan 10, 2013 at 1:38
  • 1
    I don't use Qt, but the error looks like all you need to do is convert it to a QString, which has a const char * constructor. Commented Jan 10, 2013 at 1:38
  • @NekkoRivera, While the answer is more proper than my comment, what I intended was setText(sentence.c_str()). Commented Jan 10, 2013 at 1:44

1 Answer 1

3

From QLabel reference, setText function takes const QString& as input parameter, but you passed in std::string. you could construct a QString object from std::string then pass to it.

For example:

ui->sentenceDisplay->setText(QString::fromStdString(sentence));
Sign up to request clarification or add additional context in comments.

2 Comments

Huh, I just saw the constructor for const char *, +1. Anyway, I'd personally go for setText(QString::fromStdString(sentence)).
Awesome guys thanks! Everyone helped me out so much. I didn't even realize that it took a QString I haven't used Qt in a while. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.