【发布时间】:2019-05-16 16:20:25
【问题描述】:
我的 Qt 应用程序中有一个自定义 QGraphicsScene(我的类称为 MainScene)。这个场景包含一些 Rect 项目,它们被放置在一个网格中
见图片№1
另外,我可以动态改变这个矩形网格的大小
图片№2
此外,我希望这个网格适合大小,所以每次我按下调整大小按钮 (picture №2) 时,场景都应该适合picture №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
你能告诉我,为什么会这样吗?有什么办法可以解决吗?
更新: 这就是我创建网格的方式:
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 对象的向量。
【问题讨论】:
-
显示您是如何创建网格的
-
@eyllanesc 见 UPD
-
MainScene 是 QGraphicsScene 吗?
-
@eyllanesc 是的。对不起,我没有匹配它。我会改正的
标签: c++ qt qt5 qgraphicsview qgraphicsscene