首页 > 解决方案 > 如何更改 QComboBox 的文本颜色和字体

问题描述

我正在尝试更改 QComboBox 的文本颜色。我一直在使用样式表或调色板。但是,他们更改了 Dropbox 中所有文本项的颜色。我想仅更改组合框当前选定文本的颜色和字体,而不是 Dropbox。请帮助我如何更改它们并向我展示一些示例代码。谢谢你。

// It is my code:
QStringList itemList;
itemList << "item1" << "item2" << "item3" << "item4" << "item5";

ui->comboBox->addItems(itemList);
ui->comboBox->setCurrentIndex(2);
ui->comboBox->setItemData(2, QColor(Qt::red), Qt::TextColorRole);

// this is the ways to use stylesheet
// ui->comboBox->setStyleSheet("QComboBox { color: blue; font-weight: bold; }");

// this is the ways to use QPalette
QPalette pal = ui->comboBox->palette();
pal.setColor(QPalette::Text, Qt::blue);
ui->comboBox->setPalette(pal);

标签: textfontscolorsqcombobox

解决方案


最简单的解决方案是:

QFont font(QStringLiteral("Times"), 16);    

QComboBox *box = new QComboBox;
box->setFont(font);
box->addItem("Hello");
box->addItem("Qt!");

/************ solution *************/
box->setEditable(true);
QLineEdit *edit = box->lineEdit();
edit->setReadOnly(true);

font.setBold(true);
edit->setFont(font);

QPalette pal = edit->palette();
pal.setColor(QPalette::Text, Qt::red);
edit->setPalette(pal);
/***********************************/

box->move(qApp->primaryScreen()->availableGeometry().center() - box->geometry().center());
box->show();

结果:

在此处输入图像描述

在此处输入图像描述

样式表呢?

不幸的是,我无法给出使用样式表的工作示例,但这里有一些指向样式表文档的有用链接:

通过样式表自定义 QComboBox

Qt 样式表参考


推荐阅读