PDA

View Full Version : I imitated Image Viewer example but...



sincnarf
14th October 2007, 15:31
I exactly copied all the stuff from the Image Viewer example of Qt, except for the constructor. I modified it the constructor so it would auto load an image coming from another mainwindow that calls




ImageViewer imageViewer(&image);




Now I am having trouble with the class because it closes/quits... and I am sure that that class's method show() ( opens for x milliseconds then closes).

I've read this
http://www.qtcentre.org/forum/f-qt-programming-2/t-qapplication-instance-9403.html/?highlight=QApplication
and it says two QApplication can't run at the same time. So how am I going to let the ImageViewer window stay (not instantly quit on show()). ? Because as of now I can't manually close it.. it closes on itself?

Here goes the modified constructor of ImageViewer.



ImageViewer::ImageViewer(const QImage *image) {
imageLabel = new QLabel;
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);

scrollArea = new QScrollArea;
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageLabel);
setCentralWidget(scrollArea);

createActions();
createMenus();

setWindowTitle(tr("Image Viewer"));
resize(500, 400);

// this is where the opening of the passed const image starts

if (image->isNull() || image == 0) {
QMessageBox::information(this, tr("Image Viewer"),
tr("Cannot load the image."));
return;
}

QPixmap pixmap = QPixmap::fromImage(*image);

imageLabel->setPixmap(pixmap);
scaleFactor = 1.0;

printAct->setEnabled(true);
fitToWindowAct->setEnabled(true);
updateActions();

if (!fitToWindowAct->isChecked())
imageLabel->adjustSize();

// suddenly closes ! ! !
show();
}


I've also read http://www.qtcentre.org/forum/f-qt-programming-2/t-qgraphicsview-7336.html/?highlight=maptoscene so. how do I NOT destroy the ImageViewer after calling its constructor?

marcel
14th October 2007, 16:11
Oh, now I get it.
You were creating the image viewer on the stack:


ImageViewer imageViewer(&image);


Create it on the heap, so it won't be destroyed as soon as the scope in which you created it ends:


ImageViewer *imageViewer = new ImageViewer(&image);



Or make it a class member.

sincnarf
14th October 2007, 17:07
that was fast.. So basic... I'm really sorry. Getting pressured here. Thanks again

bpetty
1st November 2007, 14:38
This may come over as nitpicking but in my opinion you are doing too much logic in your constructor... from a software engineering standpoint. I *try* to write my constructors such that they only initialize member variables. If I need more than that I will usually write an Init() method. Your case is a little different... modulizing it might be a good start.