0

我有一个 QGraphicsView,因为我有一个 QGraphicsScene,因为我有一个 QLabel,并且我将 .png 图片作为 QPixmap 设置到 QLabel 中。.png 在 background.qrc 资源文件中设置。我的 QLabel 的尺寸是 600x400。没有像素图也没关系,QGraphicsScene 的大小也是 600x400。但是当我将像素图设置为 QLabel 并对其进行缩放时,它失败了。QLabel 的大小是一样的,像素图在 QLabel 内缩放得很好,并且只在其中可见,但是 QGraphicsScene 采用了 QPixmap 的实际大小,即 720x720。所以 QLabel 在 QPixmap 的大小正确时是可见的,但它周围有一个灰色的地方,因为场景更大。我该如何解决这个问题并让它工作?我希望 QGraphicScene 保持 QLabel 的大小。

这是代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPixmap>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QGraphicsView *myView = new QGraphicsView(this);
    QGraphicsScene *myScene= new QGraphicsScene();
    QLabel *myLabel= new QLabel();
    myLabel->setBaseSize(QSize(600, 400));
    myLabel->resize(myLabel->baseSize());
    myLabel->setScaledContents(true);
    QPixmap pixmapBackground(":/new/cross.png");
    myLabel->setPixmap(pixmapBackground);
    myScene->addWidget(myLabel);
    myView->setScene(myScene);
    setCentralWidget(myView);
}

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

1 回答 1

1

从您的示例代码中,您没有设置场景的大小。您可以通过调用setSceneRect来做到这一点。如文档所述,当未设置 rect 时:-

如果未设置,或者如果设置为 null QRectF,sceneRect() 将返回自场景创建以来场景中所有项目的最大边界矩形(即,当项目添加到场景中或在场景中移动时增长的矩形,但是永不收缩)。

因此,在不设置场景矩形的情况下,当标签添加到场景中时,其大小会发生变化,如本例所示

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QLabel>
#include <QPixmap>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView *myView = new QGraphicsView;
    QGraphicsScene *myScene= new QGraphicsScene();

    // constrain the QGraphicsScene size
    // without this, the defect as stated in the question is visible
    myScene->setSceneRect(0,0,600,400); 

    QLabel *myLabel= new QLabel;    
    myLabel->setBaseSize(QSize(600, 400));
    myLabel->resize(myLabel->baseSize());
    myLabel->setScaledContents(true);

    QPixmap pixmapBackground(720, 720);
    pixmapBackground.fill(QColor(0, 255, 0)); // green pixmap

    myLabel->setPixmap(pixmapBackground);
    myScene->addWidget(myLabel);
    myView->setScene(myScene);
    myView->show();

    return a.exec();
}

这应该会产生正确的场景大小,如下所示: -

在此处输入图像描述

正如评论中所讨论的,上面的示例代码在 OS X 上按预期工作,但在 Windows 10 上执行时似乎仍然存在问题。

于 2016-08-02T09:12:37.920 回答