我在Qt应用程序中有一个定制的QGraphicsScene (我的类称为MainScene)。此场景包含一定数量的Rect项,这些项被放置在网格中。
见图№1

此外,我还可以动态地更改这个Rect网格的大小。
图片№2

此外,我希望这个网格符合大小,所以每次我按下调整大小按钮(图片№2)时,场景都应该与图片№1中的大小相匹配。我使用以下代码实现它:
void MainWindow::on_resizeButton_clicked()
{
int h = ui->heightSpinBox->value(); //height of the grid
int w = ui->widthSpinBox->value(); //width of the grid
scene->resize(h, w); //adding required amount of rects
ui->graphicsView->fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);
ui->graphicsView->centerOn(0, 0);
}问题是:当我选择高度和宽度时,如果新高度大于当前高度,新宽度大于当前宽度(例如,当前网格为20x20,并将其调整为30x30),则工作正常,但当我选择小于当前大小的高度和宽度(例如,当前网格为30x30,而我将其调整为20x20)时,它不能按我的要求工作。
图片№3

你能告诉我为什么会发生这种事吗?有什么办法可以解决吗?
UPD:我就是这样创建网格的:
void MainScene::resize(int rows, int cols)
{
clearScene(rows, cols);
populateScene(rows, cols);
}
void MainScene::clearScene(int rows, int cols)
{
if(rows < roomHeight)
{
for(int i = rows; i < roomHeight; ++i)
{
for(int j = 0; j < roomWidth; ++j)
{
removeItem(room[i][j]);
delete room[i][j];
}
}
room.resize(rows);
roomHeight = rows;
}
if(cols < roomWidth)
{
for(int i = 0; i < roomHeight; ++i)
{
for(int j = cols; j < roomWidth; ++j)
{
removeItem(room[i][j]);
delete room[i][j];
}
room[i].resize(cols);
}
roomWidth = cols;
}
}
void MainScene::populateScene(int rows, int cols)
{
if(rows > roomHeight)
{
room.resize(rows);
for(int i = roomHeight; i < rows; ++i)
{
room[i].resize(roomWidth);
for(int j = 0; j < roomWidth; ++j)
{
room[i][j] = new GraphicsCell();
room[i][j]->setPos(j * 30, i * 30);
addItem(room[i][j]);
}
}
roomHeight = rows;
}
if(cols > roomWidth)
{
for(int i = 0; i < roomHeight; ++i)
{
room[i].resize(cols);
for(int j = roomWidth; j < cols; ++j)
{
room[i][j] = new GraphicsCell();
room[i][j]->setPos(j * 30, i * 30);
addItem(room[i][j]);
}
}
roomWidth = cols;
}
}GraphicsCell是我的自定义类,它是从QObject和QGraphicsItem派生的。room是GraphicsCell对象的向量。
发布于 2018-12-15 19:38:38
当您添加项目时,如果它们不在sceneRect中,那么sceneRect就会增加,这是在添加30x30时发生的,但是当您传递20x20时,它不会减少,所以场景仍然很大,所以您可以查看QScrollBar,所以在这种情况下,解决方案是将场景的大小更新到itemsBoundingRect()。
void MainWindow::on_resizeButton_clicked()
{
int h = ui->heightSpinBox->value(); //height of the grid
int w = ui->widthSpinBox->value(); //width of the grid
scene->resize(h, w); //adding required amount of rects
ui->graphicsView->fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);
scene->setSceneRect(scene->itemsBoundingRect()); // <---
} https://stackoverflow.com/questions/53795925
复制相似问题