我想从graphicObject创建一个像素图,所以我可以将像素图设置为图标

我有一个从Block派生的QGraphicsPathItem类,我尝试使用:

Block *block = new Block();

QRect rect = block->boundingRect().toRect();

QPixmap pixmapItem;
pixmapItem.copy(rect);

QListWidgetItem *item = new QListWidgetItem;
item->setIcon(QPixmap(pixmapItem));

但像素图似乎为空。

有没有办法从graphicObject或graphicItem中获取图像/图标?

最佳答案

您必须使用paint() QGraphicsItem 方法来获取呈现:

static QPixmap QPixmapFromItem(QGraphicsItem *item){
    QPixmap pixmap(item->boundingRect().size().toSize());
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QStyleOptionGraphicsItem opt;
    item->paint(&painter, &opt);
    return pixmap;
}

例子:
#include <QApplication>
#include <QGraphicsPathItem>
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QListWidget>

static QPixmap QPixmapFromItem(QGraphicsItem *item){
    QPixmap pixmap(item->boundingRect().size().toSize());
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QStyleOptionGraphicsItem opt;
    item->paint(&painter, &opt);
    return pixmap;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    QHBoxLayout lay(&w);
    QListWidget listWidget;
    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    int counter = 0;
    for(const QColor & color : {QColor("red"), QColor("blue"), QColor("green")}){
        QPainterPath p;
        p.addRoundedRect(0, 0, 150, 50, 2, 2);
        QGraphicsPathItem *block = scene.addPath(p);
        block->setBrush(QBrush(color));
        block->setFlag(QGraphicsItem::ItemIsMovable);
        block->setFlag(QGraphicsItem::ItemIsSelectable);
        block->setPos(counter*QPointF(10, 10));

        // get QPixmap from item
        QPixmap pixmap = QPixmapFromItem(block);

        QListWidgetItem *l_item = new QListWidgetItem(color.name());
        listWidget.addItem(l_item);
        l_item->setIcon(QIcon(pixmap));
        counter++;
    }
    lay.addWidget(&listWidget);
    lay.addWidget(&view);
    w.show();
    return a.exec();
}

c&#43;&#43; - Qt-有没有办法将图形项目转换为像素图?-LMLPHP

关于c++ - Qt-有没有办法将图形项目转换为像素图?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50358535/

10-09 05:59