我有一个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;
}
发布于 2016-08-02 09:12:37
根据您的示例代码,您没有设置场景的大小。您可以通过调用setSceneRect来完成这一任务。如文档所述,当未设置rect时:
如果未设置,或者设置为空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上正常工作,但是在Windows 10上执行时仍然存在问题。
https://stackoverflow.com/questions/38704916
复制相似问题