Tuesday, July 20, 2010

Segmentation Fault when saving a QImage in Qt 4.6

This function should save its QImage image to a file either specified by the user or that it was opened from.
void ImageDocument::save(QString file)
{
if (file.isEmpty())
file = filename;
cout << qPrintable(file) << endl;
if (this->image.save(file, "PNG")) {
if (!this->undoStack->isClean())
this->undoStack->setClean();
filename = file;
}
}

If I were to use it with the following, it would cause a segmentation fault:
void PixelEasel::saveAs()
{
QString fileName(QFileDialog::getSaveFileName(this, tr("Save As"),
QDir::currentPath(),
tr("Images (*.png *.gif)")));
if (fileName.isEmpty())
return;
activeDocument()->save(fileName);
saveAct->setEnabled(!undoGroup->isClean());
}

Whereas the exact same code, except for the manual specification of the file path, will succeed.

Apparently, I am a moron and wrongly assumed that QMdiArea::activeSubWindow() will give you the sub-window if the area of focus is the top-level window menu. (Hint: QMdiArea::currentSubWindow() will do the trick). It is apparent I have not been using C++ in such a long time, because Qt was letting me execute methods on an object that was cast from a NULL pointer. I thought that would throw an exception earlier rather than when it went and tried to look for class members that didn't officially exist.

No comments:

Post a Comment