PDA

View Full Version : QMainWindow: problem changing centralWidget



Caius Aérobus
4th October 2007, 10:43
Hello,
I get a segmentation fault on the setCentralWidget() call in the SetBackground() slot, that is when the QMainWindow attempts to change the central widget. I do know that it tries to delete the widget but do not understand how to cope with that. Please help!

class myClass : public QMainWindow
{
Q_OBJECT

QImage fond;
QLabel *wfond;
};

myClass::myClass()
: QMainWindow()
{
this->fond.load("somepic.jpg");
this->wfond = new QLabel;
this->wfond->setPixmap(QPixmap::fromImage(this->fond));
this->setCentralWidget(this->wfond);
}

void
myClass::SetBackground(QImage im)
{
this->fond = im;
this->wfond = new QLabel;
this->wfond->setPixmap(QPixmap::fromImage(this->fond));
this->setCentralWidget(this->wfond);
}

wysota
4th October 2007, 10:54
Did you try debugging? What does the backtrace say?

rajesh
4th October 2007, 11:28
try to use QImage pointer.
class myClass : public QMainWindow
{
Q_OBJECT

QImage *fond; //use pointer
QLabel *wfond;
};

myClass::myClass()
: QMainWindow()
{
fond = new QImage; //allocate here.
this->fond->load("somepic.jpg");
...
}

why you using this pointer everywhere?

Caius Aérobus
4th October 2007, 11:59
try to use QImage pointer.
class myClass : public QMainWindow
{
Q_OBJECT

QImage *fond; //use pointer
QLabel *wfond;
};

myClass::myClass()
: QMainWindow()
{
fond = new QImage; //allocate here.
this->fond->load("somepic.jpg");
...
}

why you using this pointer everywhere?

Here is my new code, modified according to your advice:

class myClass : public QMainWindow
{
Q_OBJECT

QImage *fond;
QLabel *wfond;
};

myClass::myClass()
: QMainWindow()
{
this->fond = new QImage("somepic.jpg");
this->wfond = new QLabel;
this->wfond->setPixmap(QPixmap::fromImage(*this->fond));
this->setCentralWidget(this->wfond);
}

void
myClass::SetBackground(QImage im)
{
this->fond = new QImage(im);
this->wfond = new QLabel;
this->wfond->setPixmap(QPixmap::fromImage(*this->fond));
this->setCentralWidget(this->wfond);
}

but stil the same segmentation fault on setCentralWidget() !

jpn
4th October 2007, 12:05
try to use QImage pointer.
QImage is an implicitly shared (http://doc.trolltech.com/latest/shared.html) class. There is no advantage in allocating it on the heap. It only makes things unnecessarily more complicated.

Caius Aérobus: Why not just change the pixmap? There is no need to create a new QLabel every time.

rajesh
4th October 2007, 12:09
just for testing , try following code, is it working or not?
void myClass::SetBackground(QImage im)
{
QLabel *center = new QLabel("test");
setCentralWidget(center);
}

Caius Aérobus
4th October 2007, 13:00
Hmmm, I suppose I have fixed the problem. I use Qt 4.1 and I tried it on another system on which Qt 4.3 is installed and... everything works fine! So probably a bug in Qt 4.1. I will upgrade ASAP.
Thanks to all of you for trying to help me!
Best regards.