Как я могу установить собственный текст для QLabel в C ++?

Я работаю над симулятором C ++ / Qt, который объединяет страницу параметров. В конце параметров QLabel уведомляет пользователя, верны ли введенные данные или нет. Этот текст должен отображаться с произвольным цветом, поэтому я реализовал это:

ParametersDialog.h

#include <iostream>
#include <QtWidgets>

using namespace std;

class ParametersDialog: public QDialog {
    Q_OBJECT

    public:
        ParametersDialog(QWidget *parent = nullptr);
        ~ParametersDialog();

    ...

    private:
        QLabel *notificationLabel = new QLabel;
        ...
        void notify(string message, string color);
};

ParametersDialog.cpp

#include "<<src_path>>/ParametersDialog.h"

ParametersDialog::ParametersDialog(QWidget *parent): QDialog(parent) {
    ...
    notify("TEST TEST 1 2 1 2", "green");
}

...

void ParametersDialog::notify(string message, string color = "red") {
    notificationLabel->setText("<font color=" + color + ">" + message + "</font>");
}

Я не понимаю, почему это дает мне эту ошибку:

D:\dev\_MyCode\SM_Streamer\<<src_path>>\ParametersDialog.cpp:65:79: error: no matching function for call to 'QLabel::setText(std::__cxx11::basic_string<char>)'
  notificationLabel->setText("<font color=" + color + ">" + message + "</font>");
                                                                               ^

Я понимаю, что при объединении строк был создан элемент basic_string<char>, который нельзя задать как текст QLabel.

Какая может быть самая простая реализация моего notify метода?


person 0009laH    schedule 26.05.2020    source источник
comment
basic_string<char> - это просто std::string, но метод принимает QString   -  person 463035818_is_not_a_number    schedule 26.05.2020
comment
Я пробовал это решение, но оно дает аналогичную ошибку: notificationLabel->setText(QString("<font color=" + color + ">" + message + "</font>"));   -  person 0009laH    schedule 26.05.2020
comment
Да, работает, я забыл, что QString нельзя собрать так, как я :) Большое спасибо   -  person 0009laH    schedule 26.05.2020


Ответы (1)


проблема в том, что std :: string и QString не могут быть объединены напрямую ...

уловку можно сделать:

QString mx = "<font color=%1>%2</font>";
notificationLabel->setText(mx.arg(color.c_str(), message.c_str()));
person ΦXocę 웃 Пepeúpa ツ    schedule 26.05.2020