简体   繁体   中英

Qt string problems

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM