QImage显示清晰的像素

时间:2014-10-18 22:23:00

标签: c++ qt qimage

我有一个布尔值的矩阵,我试图用QImage绘制。我已经从uchar向量中导入了图像,其中0和255值分别为false和true。我希望黑色和白色方块代表不同的值,但我会在the picture here中显示像​​素之间的模糊。你能告诉我如何消除模糊并显示更大的像素吗?

代码如下:

for(int i=0; i<world.size(); ++i) {
    if(world[i] == true) 
        world_uchar[i] = 255;
    else 
        world_uchar[i] = 0;
}

QImage img(world_uchar, cols, rows, QImage::Format_Indexed8);

QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(img));
myLabel.setScaledContents(true);
myLabel.show();

1 个答案:

答案 0 :(得分:0)

不是使用setScaledContents,而是每次窗口大小更改或图像更改时都会绘制一个已调整大小的图像。请参阅下面的示例(在该示例中,我使用了QMainWindow):

class MainWindow : public QMainWindow
{
    Q_OBJECT
...
private:
    QPixmap pixmap;
};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->label->setAlignment(Qt::AlignCenter);
    //SetMinminumSize to ensure that the QLabel
    //can be resized
    ui->label->setMinimumSize(10, 10);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QBitArray world(256, false);
    uchar *world_uchar = new uchar[world.size()];
    int cols, rows;
    cols = rows = (int)qSqrt(world.size());

    for (int i = 0; i < world.size(); i += 2)
        world.setBit(i, (qrand() % ((1 + 1) - 0) + 0));

    for (int i = 0; i < world.size(); i++)
    {
        if (world[i])
            world_uchar[i] = 255;
        else
            world_uchar[i] = 0;
    }

    QImage img(world_uchar, cols, rows, QImage::Format_Indexed8);

    pixmap = QPixmap::fromImage(img);
    OnResize();
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    OnResize();
}

void MainWindow::OnResize()
{
    if (!pixmap.isNull())
        ui->label->setPixmap(pixmap.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::FastTransformation));
}