【发布时间】:2011-12-29 13:03:16
【问题描述】:
我想做的是:
我有一个带有 QGraphicsView 的小 GUI。在此图形视图中,我加载了一张图片:
// m_picture is QPixmap
// image is QImage
// m_graphic is QGraphicsScene
// graphicsView is QGraphicsView
m_picture.convertFromImage(image);
m_graphic->addPixmap(m_picture);
ui->graphicsView->setScene(m_graphic);
这不会导致任何问题,我总是可以毫无问题地加载新图像。 现在除了只显示图片之外,我还想让用户能够在它们上绘制一个矩形(以“聚焦”特定区域)。实际上,用户只需在 GUI 上的四个文本框中输入坐标(x、y、width、heigth)。提供坐标后,用户按下按钮,将显示以下坐标处的矩形。 我用这段代码完成了这个:
void tesseract_gui::show_preview_rect()
{
int x,y,h,w;
x = ui->numBox_x->value();
y = ui->numBox_y->value();
h = ui->numBox_h->value();
w = ui->numBox_w->value();
if( rect_initialized )
{
m_graphic->removeItem(m_rect);
}
else
{
rect_initialized = true;
}
m_rect->setPen(QPen(Qt::red));
m_rect->setRect(x,y,h,w);
m_graphic->addItem(m_rect);
return;
}
remove 调用是因为我总是只想显示一个矩形。 现在正如我提到的,这很好用。但是,如果用户现在加载另一张图片(在我的帖子顶部调用),当我尝试绘制一个新矩形时程序会崩溃。一世 在调用
时出现分段错误m_rect->setPen(QPen(Qt::red));
如果我打电话
m_graphic->removeItem(m_rect);
加载新图片后,我得到了
QGraphicsScene::removeItem: item 0x8c04080 的场景 (0x0) 与这个场景 (0x8c0a8b0) 不同
然后它在 setPen 处以相同的错误崩溃。
我不明白的是,我没有改变场景。我只是向它添加另一张图片(或覆盖它)。 那么有什么建议我可以如何做到这一点吗?
最好的问候
// 编辑:
我每次都尝试使用这样的新矩形:
void tesseract_gui::show_preview_rect()
{
int x,y,h,w;
x = ui->numBox_x->value();
y = ui->numBox_y->value();
h = ui->numBox_h->value();
w = ui->numBox_w->value();
m_graphic->clear();
m_graphic->addRect(x,y,h,w);
return;
}
问题在于,使用 clear() 调用它还会从我的 GraphicsView 中清除图片本身...所以那里没有解决方案
// 编辑:
按照建议,我摆脱了这样的警告:
if( m_rect->scene() != 0 )
{
m_graphic->removeItem(m_rect);
}
m_rect->setPen(QPen(Qt::red));
m_rect->setRect(x,y,h,w);
m_graphic->addItem(m_rect);
我知道这不是最好的方法,但我也尝试过这种方法(对我不起作用):
我在构造函数中添加了该项:
m_graphic->addItem(m_rect);
然后
m_rect->setPen(QPen(Qt::red));
m_rect->setRect(x,y,h,w);
m_graphic->update();
并且我一如既往地收到“相同”错误(程序在 m_rect->setPen() 处崩溃) 因此,当我已经将矩形添加到图形中时,似乎总是会出现问题,然后更改 m_graphic 的图像,然后对 m_rect 进行任何操作。 (实际上我猜 m_graphic 拥有 m_rect 的所有权,所以这会导致分段错误......?)
【问题讨论】:
标签: c++ qt user-interface graphics