【问题标题】:How can I set custom text to a QLabel in C++?如何在 C++ 中将自定义文本设置为 QLabel?
【发布时间】:2020-09-13 00:30:24
【问题描述】:

我正在开发一个集成参数页面的 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>");
                                                                               ^

我了解我的字符串连接创建了一个无法设置为 QLabel 文本的 basic_string&lt;char&gt; 元素。

我的notify 方法最简单的实现可能是什么?

【问题讨论】:

  • a basic_string&lt;char&gt; 只是 std::string 但该方法采用 QString
  • 我已经尝试过这个解决方案,但它给了我一个类似的错误:notificationLabel-&gt;setText(QString("&lt;font color=" + color + "&gt;" + message + "&lt;/font&gt;"));
  • 这能回答你的问题吗? stackoverflow.com/questions/1814189/…
  • 是的,它有效,我忘记了 QString 不能像我一样构建 :) 非常感谢

标签: c++ c++11 qt5 qlabel


【解决方案1】:

问题在于 std::string 和 QString 不能直接连接...

可以做一个技巧:

QString mx = "<font color=%1>%2</font>";
notificationLabel->setText(mx.arg(color.c_str(), message.c_str()));

【讨论】:

    猜你喜欢
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2019-05-28
    • 2019-05-23
    • 2018-05-15
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多