S
S
Sergey Chistyakov2014-12-18 09:23:44
Qt
Sergey Chistyakov, 2014-12-18 09:23:44

Why doesn't it show if QWidget::show() is called with a dot?

Let's say I have a class MyWidgetand it's inherited from QWidget. I create my only handmade widget my. I put a button in it. When you click on it, a signal is sent to my. There at this time there is a slot that receives the sent signal and in response creates QWidgetand shows it as a separate element.
Class description:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    void show_widget( void )
    {
        QWidget w;

        QLineEdit *line = new QLineEdit;

        QVBoxLayout *vertical = new QVBoxLayout;
        vertical->addWidget(line);

        w.setLayout(vertical);
        w.setGeometry(100, 100, 300, 200);
        w.show();
    }
};

#endif // WIDGET_H

And maine:
#include <QApplication>
#include <QtGui>

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

    QPushButton *btn = new QPushButton("Show widget");
    QObject::connect(btn, SIGNAL(clicked()),
                     &w, SLOT(show_widget()));

    QHBoxLayout *buttons = new QHBoxLayout;
    buttons->addWidget(btn);

    w.setLayout(buttons);
    w.setGeometry(200, 100, 800, 500);
    w.show();

    return a.exec();
}

I expect for this case that a window will pop up when clicked, but it wasn’t there. But it’s enough for me to replace the dot with an arrow and, of course, the object with a pointer to the object, and (lo and behold!) everything works:
void Widget::show_widget( void )
{
    QWidget *w = new QWidget;

    QLineEdit *line = new QLineEdit;

    QVBoxLayout *vertical = new QVBoxLayout;
    vertical->addWidget(line);

    w->setLayout(vertical);
    w->setGeometry(100, 100, 300, 200);
    w->show();
}

Purely academic question: why so?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2014-12-18
@piro1107

it’s enough for me to replace the dot with an arrow and, of course, the object with a pointer to the object and (oh miracle!) Everything works

The most important thing did not say: "and the QWidget object on the stack of the current function on the object on the heap".
Because in the first case, the widget is destroyed when the show_widget function exits, and in the second case, it remains to hang out in the heap. Exit occurs immediately upon return from QWidget::show, and the call itself is non-blocking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question