text - 如何更改 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);
解决方案
最简单的解决方案是:
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();
结果:
样式表呢?
不幸的是,我无法给出使用样式表的工作示例,但这里有一些指向样式表文档的有用链接:
推荐阅读
- image - 测试文件名是否在项目文件中的任何位置的最佳方法是什么
- javascript - 什么是 DOMElement.shadowRoot?
- android - 如何在 android sdk 29 或最低版本的启动设备上启动服务?
- python - map() 如何与 python 中的字典一起使用?
- php - 未收到来自 mail() 函数的退回邮件
- reactjs - 如何在 React 的 Apex 图表中定义自定义工具提示?
- android - 使用 SQLite 数据库启动应用程序时出现 NullPointerException
- .net-framework-version - 使用命令行更改 .net 框架构建引擎版本
- questdb - 如何从 OSGi 包加载 QuestDB 函数?
- c - C语言中自身的Typedef Struct