C++ Qt 设置 QLineEdit 的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27283435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:46:08  来源:igfitidea点击:

Qt Set Background Color of QLineEdit

c++qtbackgroundqlineeditpalette

提问by David Ludwig

I'm trying to change the background color of the QLineEditand I can't figure it out at all.

我正在尝试更改 的背景颜色,但QLineEdit我根本无法弄清楚。

I tried using stylesheetsoriginally like this

我试着用stylesheets原来这样

QLineEdit *le = new QLineEdit();
le->setStyleSheet("background:#000;");

but that didn't do anything. I tried using QPalettelike this

但这没有做任何事情。我试着用QPalette这样的

QPalette palette;
palette.setColor(QPalette::Base, Qt::black);
palette.setColor(QPalette::Background, Qt::black);
le.setPalette(palette);    

but this didn't do anything either. I've been looking all day and can't find anything. am I doing something wrong or is there another way to do it?

但这也没有任何作用。我找了一整天,什么也没找到。我做错了什么还是有其他方法可以做到?

采纳答案by Iuliu

Works fine for me:

对我来说很好用:

QLineEdit *le = new QLineEdit();
le->setStyleSheet("QLineEdit { background: rgb(0, 255, 255); selection-background-color: rgb(233, 99, 0); }");

回答by Nejat

You can set the background and text colors of line edit by setting the palette like :

您可以通过设置调色板来设置行编辑的背景和文本颜色:

QLineEdit *le = new QLineEdit();

QPalette palette;
palette.setColor(QPalette::Base,Qt::black);
palette.setColor(QPalette::Text,Qt::white);
le->setPalette(palette);

回答by Tomas Tintera

Your code is almost correct. Only QLine edit uses the Base color. So if you do not want to replace existing stylesheet which can contain borders padding and margin and you want to change background only, use QPalette:

你的代码几乎是正确的。只有 QLine 编辑使用基本颜色。因此,如果您不想替换可以包含边框填充和边距的现有样式表,并且只想更改背景,请使用 QPalette:

QPalette palette = _ui->lnSearch->palette();
palette.setColor(QPalette::Base, Qt::green);
_ui->lnSearch->setPalette(palette);

Thanks to: https://forum.qt.io/topic/64568/why-setting-background-color-of-qlineedit-has-no-effect

感谢:https: //forum.qt.io/topic/64568/why-setting-background-color-of-qlineedit-has-no-effect

回答by Brandon

I had to use background-color from standard css like this:

我必须使用标准 css 中的背景颜色,如下所示:

QLineEdit* edit = new QLineEdit();
edit->setStyleSheet("QLineEdit {background-color: black;}");

I am using Qt 5.4

我正在使用 Qt 5.4