简体   繁体   English

Qt小部件具有类似QLineEdit的背景

[英]Qt Widget with QLineEdit-like background

I'm looking to create a custom widget where part of it is a "background" that looks like a QLineEdit (or QProgressBar), 我正在寻找一个自定义小部件,其中一部分是一个看起来像QLineEdit(或QProgressBar)的“背景”,

eg 例如 but without the text. 但没有文字。

I've come up with a couple of hacky ways to do this, but neither of them seem like a good solution: 我想出了几种方法来实现此目的,但似乎都不是一个好的解决方案:

1. 1。

QPainter painter(this);

int penwidth = painter.pen().width();
int width = this->width();
int height = this->height() - 20;
QPoint tl(penwidth / 2, penwidth / 2 + 10);
QPoint bl(penwidth / 2, height - penwidth);
QPoint tr(width - penwidth, penwidth / 2);
QPoint br(width - penwidth, height - penwidth);
QRect rect(tl, br);

QStyleOptionFocusRect option;
option.initFrom(this);
option.backgroundColor = palette().color(QPalette::Button);
option.rect = rect;
this->style()->drawControl(QStyle::CE_ProgressBarGroove, &option, &painter, this);

This has the disadvantage of not being fully controllable, especially when inside a layout as I intend it to be 这具有无法完全控制的缺点,尤其是在按我希望的布局内部放置时

2. 2。

Using a QLineEdit widget but setting it to NoFocus and ReadOnly. 使用QLineEdit小部件,但将其设置为NoFocus和ReadOnly。

This seems like overkill to me, as I'll never want any of the text functionality 在我看来,这似乎太过分了,因为我永远都不需要任何文本功能

What is the best solution to this? 最好的解决方案是什么?

Use QLabel with special stylesheet : 使用带有特殊stylesheet QLabel

ui->label->setText("");
ui->label->setStyleSheet("QLabel{ border: 1px solid gray; background-color:white; border-radius:2px}");

Stylesheet: 样式表:

QLabel
{
 border: 1px solid gray;
 background-color:white;
 border-radius:2px
}

QLabel has no any other unnecessary things so it is better than QLineEdit or QProgressBar . QLabel没有其他不必要的东西,所以它比QLineEditQProgressBar更好。

Result: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM