Home > OS >  How to overlay 2 Images in QT
How to overlay 2 Images in QT

Time:06-07

I have 2 images that I load in QImage and my question is : How can I overlay these 2 images in the simplest way, to then save it in a QPixmap ?

Here are the following images : potion stack multiplier

And the awaited result : result

(The final image will be used in a QTableView to show the user if it has more of the same potion)

CodePudding user response:

I was able to find the answer on my own after some more research. Here is my code that I came up with (if you can do it better I would like to see it because I would like to implement any better approach if there is any):

    QPixmap base = QPixmap::fromImage(QImage("Your 1st img"));
    QPixmap overlay = QPixmap::fromImage(QImage("your 2nd img"));
    QPixmap result(base.width(), base.height());
    result.fill(Qt::transparent); // force alpha channel
    {
        QPainter painter(&result);
        painter.drawPixmap(0, 0, base);
        painter.drawPixmap(0, 0, overlay);
    }
    QStandardItem *pCombinedItem = new QStandardItem(); //this variable should be in the .h file if you want to conserve it further on.
    pCombinedItem->setData(QVariant(result), Qt::DecorationRole);//adding the final img into the StandardItem which we can put then into our table after we put it into a StandardItemModel like so :
    model->setItem(1,4,pCombinedItem);
    pInventory->setModel(model); //and we can put our model into our tableview
  • Related