【问题标题】:Why do I see gaps between pixmap tiles in QGraphicsView when I enable Antialiasing为什么我在启用抗锯齿时在 QGraphicsView 中看到像素图块之间的间隙
【发布时间】:2015-08-10 15:16:42
【问题描述】:

我正在使用 QGraphicsView 框架从较小的 QPixmap 图块中显示大图像。我还想启用抗锯齿,因为场景将包含行项目。为什么我在启用抗锯齿时会看到图块之间的间隙?

class MainWindow : public QWidget
{
    public:
    MainWindow(QWidget *parent = 0);

protected:
    void resizeEvent(QResizeEvent*);

private:
    QGraphicsScene* _scene;
    QGraphicsView* _view;
    qreal _scale;
    static const int _imageWidth = 512;
    static const int _imageHeight = 128;
};

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    _scene = new QGraphicsScene(this);
    _view = new QGraphicsView(_scene, this);

     //this causes gaps to appear ?
    _view->setRenderHints(QPainter::Antialiasing);

    _scene->setBackgroundBrush( QBrush( QColor( Qt::lightGray ) ) );

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->addWidget(_view);

    setWindowTitle(QString("GapsBetweenTiles- QT Version %1")
       .arg(QT_VERSION_STR));

    QImage img = QImage(_imageWidth, _imageHeight, QImage::Format_RGB32);
    img.fill(QColor(00, 50, 50));

    int offset = 0;
    for (int k=0; k < 10; ++k) {
        QGraphicsPixmapItem* pixitem = _scene->addPixmap( 
                          QPixmap::fromImage(img));
        pixitem->setTransformationMode(Qt::SmoothTransformation);
        pixitem->setPos(0, offset);
        offset += _imageHeight;
    }
    _scale = 1.0;
}

void MainWindow::resizeEvent(QResizeEvent* )
{
    int scaledWidth = (qreal)_view->width() -
                           _view->verticalScrollBar()->width() ;
    qreal scale = (qreal)scaledWidth / (qreal)_imageWidth;
    qreal scaleMult = scale / _scale;

    _view->scale(scaleMult, scaleMult);
    _scale = scale;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

【问题讨论】:

    标签: qt qgraphicsview qpixmap


    【解决方案1】:

    当缩放的图像高度 (_imageHeight * scale) 变为小数时,就会出现间隙。 每个QGraphicsPixmapItem 都被绘制为一个单独的对象。如果此类对象具有分数高度,则启用抗锯齿时会平滑边框(部分绘制分数边界线)。

    在您的情况下,有三种可能的间隙布局:

    • 如果缩放的图像高度是整数,则没有间隙
    • 如果高度的小数部分为 0.5,则 1 个有间隙对象和 1 个无间隙对象的周期性系列
    • 如果小数部分为 0.25 或 0.75,则包含 3 个有间隙对象和 1 个无间隙对象的周期性系列;这里第 2 间隙比第 1 和第 3 间隙更亮。

    所以,如果你想要完美的对象对齐,缩放高度应该是整数。 在您的示例中,当缩放宽度可被 4 整除时,缩放高度为整数。 可以通过在resizeEvent 中添加以下行来验证:

        scaledWidth = (scaledWidth / 4) * 4;
    

    顺便说一句,您可以通过删除该行来仅为QGraphicsPixmapItem 对象禁用抗锯齿:

        pixitem->setTransformationMode(Qt::SmoothTransformation);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多