如何在C ++中将自定义文本设置为QLabel?

问题描述 投票:0回答:1

我正在使用一个集成了参数页面的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方法最简单的实现是什么?

c++ c++11 qt5 qlabel
1个回答
2
投票

问题是std :: string和QString不能直接串联...

可以完成的技巧:

QString mx = "<font color=%1>%2</font>";
notificationLabel->setText(mx.arg(color.c_str(), message.c_str()));
© www.soinside.com 2019 - 2024. All rights reserved.