1

所以我制作了一个简单地制作“随机”句子的程序。它从基于使用 ctime 的种子的 7 个列表中选择一个名词和一个颜色形容词。现在我正在尝试将其转换为控制台应用程序。我的问题是我无法正确显示它。我需要将所有内容都放在一个标签上,而不是 cout。

错误:没有匹配函数调用 '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);
}
4

1 回答 1

3

从 QLabel参考中,setText 函数const QString&作为输入参数,但您传入了 std::string。您可以从 std::string 构造一个 QString 对象,然后传递给它。

例如:

ui->sentenceDisplay->setText(QString::fromStdString(sentence));
于 2013-01-10T01:41:48.060 回答