简体   繁体   中英

How to make a QGraphicsItem of translucent color?

I am working on a QT GUI that annotates pictures from a graphics View via various shapes, currently developing the easiest one which is a rectangle. I managed to add a rectangle to the image once a button is pressed and move it around with setFlag function. What i need to do now is make sure the rectangle is translucent so that the user can see what is exactly annotated. My code for the rectangle button:

void MainWindow::on_pushButton_11_clicked()  // rectangle shape creator
{
    QBrush redBrush(Qt::red);
    QBrush blueBrush(Qt::blue);
    QPen blackpen(Qt::black);
    blackpen.setWidth(3);
    rectangle = scene->addRect(-100,-100,50,50,blackpen,blueBrush);
    rectangle->setFlag(QGraphicsItem::ItemIsMovable);
}

I have researched the Qt documentation and found that the opacity function from QGraphicsItem library would probably be the solution to this but I couldn't find a way to implement this. Any help or suggestions are appriciated thanks.

There are several solutions:

  • Use the setOpacity() method that will make the items transparent in the fill and the border color.

     rectangle->setOpacity(.2);
  • If you want to set the transparency in the fill color then you must set a transparent QColor to the QBrush.

     QColor brush_color(Qt::blue); brush_color.setAlpha(50); QPen blackpen(Qt::black); blackpen.setWidth(3); rectangle = scene->addRect(-100, -100, 50, 50, blackpen, brush_color); rectangle->setFlag(QGraphicsItem::ItemIsMovable);
  • If you want to set transparency at the border then you must set a transparent QColor to the QBrush.

     QBrush blueBrush(Qt::blue); QColor black_color(Qt::black); black_color.setAlpha(50); QPen blackpen(black_color); blackpen.setWidth(3); rectangle = scene->addRect(-100, -100, 50, 50, blackpen, blueBrush); rectangle->setFlag(QGraphicsItem::ItemIsMovable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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