PDA

View Full Version : Problem with my own widget



Macok
24th January 2009, 23:10
Hello,
Im new to Qt, today i created very simple widget:
class MyWidget : public QWidget{
public:
MyWidget(QWidget *parent=0);
};

MyWidget::MyWidget(QWidget *parent)
:QWidget(parent)
{
setFixedSize(200, 100);
QPushButton *button=new QPushButton(tr("Przycisk"), this);
button->setGeometry(20, 30, 100, 50);
}
As you can see, this widget is only window and button placed in it.

I added 2 lines (10 and 11) to main.cpp to display this widget:
#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

MyWidget widget;
widget.show();

return a.exec();
}It works fine, but now I'd like to display MyWidget when user click on button placed on MainWindow.
I created "buttonDown()" slot and connected it with pushButton from MainWindow:
void MainWindow::buttonDown(){
MyWidget widget();
widget.show();
}But when I click on button nothing happens :(
So displaying this widget from main function works fine, but displaying it from another function in exactly the same way doesn't.
What should i do?

PS. The whole code have been generated by Qt Creator.
I have only added MyWidget class, and buttonDown slot.
Sorry for bad english.


@EDIT
I solved problem, but I still need help.
I replaced those lines:
MyWidget widget;
widget.show();By these:
MyWidget widget=new MyWidget;
widget->show();And it works now, but what is bad in first method?
I thought it doesn't make any difference.

rexi
24th January 2009, 23:38
MyWidget widget;
widget.show();

Here you create the widget on the stack. When the method exits, widget gets out of scope and is destroyed immediately, hence you don't see anything.



MyWidget widget=new MyWidget;
widget->show();

This creates widget on the heap, which means it won't be destroyed when the method exits.

I suggest you read up on C++ and scopes.