且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Qt:重叠的半透明的QgraphicsItem

更新时间:2023-11-20 20:15:28

Qt提供了各种混合(组合)模式,用于 QPainter 。从QGraphicsItem或QGraphicsObject派生RectItem类,允许您自定义绘画并使用组合模式,创建各种效果,如 Qt示例

Qt provides various blend (composition) modes for the QPainter. Deriving your RectItem class from QGraphicsItem or QGraphicsObject, allows you to customise the painting and using the composition modes, create various effects, as demonstrated in the Qt Example.

如果您希望两个半透明项目在不更改颜色的情况下重叠(假设它们的颜色相同),则 QPainter :: CompositionMode_Difference mode ,或CompositionMode_Exclusion将执行此操作。以下是此类对象的示例代码: -

If you want two semi-transparent items overlapping without changing the colour (assuming their colour is the same), either the QPainter::CompositionMode_Difference mode, or CompositionMode_Exclusion will do this. Here's example code of such an object: -


Header



#ifndef RECTITEM_H
#define RECTITEM_H

#include <QGraphicsItem>
#include <QColor>

class RectItem : public QGraphicsItem
{
public:
    RectItem(int width, int height, QColor colour);
    ~RectItem();

    QRectF boundingRect() const;

private:
    QRectF m_boundingRect;
    QColor m_colour;

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
};

#endif // RECTITEM_H




Implementation



#include "rectitem.h"
#include <QPainter>

RectItem::RectItem(int width, int height, QColor colour)
    : QGraphicsItem(), m_boundingRect(-width/2, -height/2, width, height), m_colour(colour)
{    
    setFlag(QGraphicsItem::ItemIsSelectable);
    setFlag(QGraphicsItem::ItemIsMovable);
}

RectItem::~RectItem()
{
}

QRectF RectItem::boundingRect() const
{
    return m_boundingRect;
}

void RectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    painter->setCompositionMode(QPainter::CompositionMode_Difference);
    painter->setBrush(m_colour);
    painter->drawRect(m_boundingRect);
}

现在,您可以创建两个相同半透明颜色的RectItem对象,并添加他们到现场

You can now create two RectItem objects of the same semi-transparent colour and add them to the scene

// assuming the scene and view are setup and m_pScene is a pointer to the scene

RectItem* pItem = new RectItem(50, 50, QColor(255, 0, 0, 128));
pItem->setPos(10, 10);
m_pScene->addItem(pItem);

pItem = new RectItem(50, 50, QColor(255, 0, 0, 128));
pItem->setPos(80, 80);
m_pScene->addItem(pItem);