QImage :: Format_mono到.png和QGraphicsScene

时间:2013-06-18 15:57:09

标签: c++ qt qgraphicsview qgraphicsscene qimage

我创建了QImage格式QImage::Format_Mono。当我尝试通过QGraphicsView将图像显示到QGraphicsScene时,视图保持不变。使用QImage函数生成的QPixmapQPixmap::fromImage()加载到场景中。我也尝试使用保存功能将QPixmap保存为PNG / JPG / BMP也无济于事。基本代码结构如下:

QGraphicsView *view = new QGraphicsView();
QGraphicsScene *scene = new QGraphicsScene();
view.setScene(scene);
QImage img(size,QImage::Format_Mono);
QVector<QRgb> v;
v.append(Qt::color0); // I have tried using black and white 
v.append(Qt::color1); // instead of color0 and 1 as well.
img.setColorTable(v);
// Do some stuff to populate the image using img.setPixel(c,r,bw)
// where bw is an index either 0 or 1 and c and r are within bounds
QPixmap p = QPixmap::fromImage(img);
p.save("mono.png");
scene->addPixmap(p);
// Code to display the view

如果我改为制作QImage::Format_RGB888的图像并用黑色或白色填充像素,则PNG / View会正确显示。

如何更新我的代码以在QImage

中显示QGraphicsView

1 个答案:

答案 0 :(得分:3)

错误是Qt::GlobalColor s(例如Qt::whiteQt::color0)的类型为QColor,而不是QRgb。 (QRgb是unsigned int的typedef)

您可以使用方法QColorQRgb转换为QColor::rgb(),或使用全局方法QRgb直接创建qRgb(r,g,b)。以下是一个完整的工作示例,用于说明monotrue还是false时非常精确的图像(并保存为PNG)。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QGraphicsView *view = new QGraphicsView();
    QGraphicsScene *scene = new QGraphicsScene();
    view->setScene(scene);

    int W = 100;
    int H = 100;
    QImage img;
    uint color0 = qRgb(255,0,0);
    uint color1 = Qt::green.rgb();
    bool mono = true;
    if(mono)
    {
        img = QImage(QSize(W,H),QImage::Format_Mono);
        QVector<QRgb> v; v << color0 << color1;
        img.setColorTable(v);
        for(int i=0; i<W; i++)
        for(int j=0; j<H; j++)
        {
            uint index;
            if(j-(j/10)*10 > 5)
                index = 0;
            else
                index = 1;
            img.setPixel(i,j,index);
        }
    }
    else
    {
        img = QImage(QSize(W,H),QImage::Format_RGB888);
        for(int i=0; i<W; i++)
        for(int j=0; j<H; j++)
        {
            uint color;
            if(j-(j/10)*10 > 5)
                color = color0;
            else
                color = color1;
            img.setPixel(i,j,color);
        }
    }

    QPixmap p = QPixmap::fromImage(img);
    p.save("mono.png");
    scene->addPixmap(p);
    view->show();

    return app.exec();
}