[英]QLabel with pixmap: prevent pixmap's color change in disabled state
How can I control the color of its pixmap in disabled label state?如何在禁用标签状态下控制其像素图的颜色?
For some bizarre reasons I need to have exactly the same look of the pixmap in active and disabled state (displayed logo).由于一些奇怪的原因,我需要在活动和禁用状态(显示徽标)下具有完全相同的像素图外观。
The pixmap I put on a QLabel with label->setPixmap(pm)
is always shown in a different color than the active state when the label is in disabled state.当标签处于禁用状态时,我放在带有
label->setPixmap(pm)
的 QLabel 上的像素图总是以与活动状态不同的颜色显示。
I struggled with the stylesheet and tried QFrame:disabled{background-color: rgba(..., ..., ..., 255);}
but the part of the label which is covered with the pixmap is always a mix with another color, which seems to come from Qt's controlling for the disabled state.我在样式表上苦苦挣扎并尝试了
QFrame:disabled{background-color: rgba(..., ..., ..., 255);}
但被像素图覆盖的标签部分总是与另一种颜色,似乎来自 Qt 对禁用状态的控制。
EDIT: It seems, Qt always mixes the pixmap color and the background color in disabled state.编辑:看来,Qt 总是在禁用状态下混合像素图颜色和背景颜色。 But Qt does not mix the colors in active state;
但是 Qt 不会在活动状态下混合颜色; then the pixmap color stays opaque.
然后像素图颜色保持不透明。 I need to switch off this mixing behavior of the disabled state.
我需要关闭禁用状态的这种混合行为。
A (not so complicated) way to achieve that, is to draw the pixmap by yourself.实现这一目标的一种(不那么复杂)的方法是自己绘制像素图。 Instead of subclassing
QLabel
and override paintEvent
, you can install an event filter in your label and listen for QPaintEvent
's only.您可以在标签中安装事件过滤器并仅侦听
QPaintEvent
,而不是子类化QLabel
和覆盖paintEvent
。
Have the filter:有过滤器:
class Filter : public QObject
{
Q_OBJECT
public:
Filter(): QObject(nullptr) {}
bool eventFilter(QObject *watched, QEvent *event);
};
In its eventFilter
method, always return false, but when you draw the pixmap:在它的
eventFilter
方法中,总是返回 false,但是当你绘制像素图时:
#include <QPaintEvent>
#include <QPainter>
#include <QStyle>
bool Filter::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::Paint)
{
QLabel * label = dynamic_cast<QLabel*>(watched);
QPainter painter(label);
QPixmap pixmap = label->pixmap()->scaled(label->size());
label->style()->drawItemPixmap(&painter, label->rect(), Qt::AlignHCenter | Qt::AlignVCenter, pixmap);
return true;
}
return false;
}
Instantiate and install the filter, something like:实例化并安装过滤器,例如:
ui->setupUi(this);
Filter * filter = new Filter();
ui->label->installEventFilter(filter);
/* don't forget to call:
delete filter;
somewhere later */
In my example code, I scaled the pixmap to fit the label size and centered it both horizontally and vertically, but you can adjust all this, according to your needs.在我的示例代码中,我缩放像素图以适应标签大小并将其水平和垂直居中,但您可以根据需要调整所有这些。
Moreover, the same filter can be installed to more than one label, since the logic works fine for them all.此外,同一个过滤器可以安装到多个标签上,因为逻辑对它们都适用。 More on event filtering here .
更多关于事件过滤在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.