0

我正在尝试从一个小部件捕获鼠标悬停事件,该小部件是 QLabel 的子类,我在其中绘制像素图。例如,我只需要通过将不透明度设置为 50% 来捕获此事件以创建透明效果。我试过setWindowOpacity(0.5)没有成功。

所以,问题是:如何修改已在 QLabel 子类的小部件中绘制的图像的不透明度?

PaintWidget.cpp

void PaintWidget::paintEvent(QPaintEvent *aEvent)
{
    QLabel::paintEvent(aEvent);

    if (_qpSource.isNull()) //no image was set, don't draw anything
        return;

    float cw = width(), ch = height();
    float pw = _qpCurrent.width(), ph = _qpCurrent.height();

    if (pw > cw && ph > ch && pw/cw > ph/ch || //both width and high are bigger, ratio at high is bigger or
        pw > cw && ph <= ch || //only the width is bigger or
        pw < cw && ph < ch && cw/pw < ch/ph //both width and height is smaller, ratio at width is smaller
        )
        _qpCurrent = _qpSource.scaledToWidth(cw, Qt::FastTransformation);
    else if (pw > cw && ph > ch && pw/cw <= ph/ch || //both width and high are bigger, ratio at width is bigger or
        ph > ch && pw <= cw || //only the height is bigger or
        pw < cw && ph < ch && cw/pw > ch/ph //both width and height is smaller, ratio at height is smaller
        )
        _qpCurrent = _qpSource.scaledToHeight(ch, Qt::FastTransformation);

    int x = (cw - _qpCurrent.width())/2, y = (ch - _qpCurrent.height())/2;

    QPainter paint(this);
    paint.drawPixmap(x, y, _qpCurrent);
}

void PaintWidget::setPixmap(const QPixmap& pixmap)
{
    _qpSource = _qpCurrent = pixmap;
    repaint();
}
4

3 回答 3

2

你是在 Linux 还是 X11 上工作?因此setWindowOpacity(0.5),仅当您的窗口管理器是复合的时才有效。此外,即使这项工作正常,您仍然会遇到麻烦。当您应用像素图时

 QPainter paint(this);
 paint.drawPixmap(x, y, _qpCurrent);

窗口的不透明度级别不能神奇地应用于像素图。您需要设置画家的不透明度,或者使用具有 alpha 通道(定义透明度)的像素图。

于 2013-01-17T13:52:59.603 回答
0

setWindowOpacity对你不起作用的原因是你已经覆盖了paintEvent. 里面有很多代码QWidgetPrivate用于设置不透明度级别和绘制您可以查看的画布,因为您已经进行了自定义绘制,您需要一种设置不透明度然后调用重绘的方法。

于 2013-01-17T13:31:51.910 回答
0

我终于找到了解决方案。我在类中创建了一个表示不透明度值的局部变量,并且还创建了下一个方法:

void PaintWidget::setOpacity(const double opacity)
{
    this->opacity = opacity;
    repaint();
}

在paintEvent方法的最后:

    [...]
    QPainter paint(this);
    paint.setOpacity(opacity);
    paint.drawPixmap(x, y, _qpCurrent);
    [...]
}
于 2013-01-17T15:03:31.047 回答