PDA

View Full Version : Own widget access causes crash



p3t3
23rd March 2011, 23:33
Hi, I created my own widget and when I'm trying to set something inside - Qt always crash. Do you know where is the problem?

main.cpp

...

MyWidget *w1 = new MyWidget();
QString text = "text";
w1->setText(text); //this always cause crash

mywidget.h


#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QLabel>
#include <QGridLayout>

class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
void SetText(QString text);

signals:

public slots:

private:
QLabel *label1;
};

mywidget.cpp


include "mywidget.h"

MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QGridLayout *layout = new QGridLayout();
QLabel *label1 = new QLabel("Name");
layout->addWidget(label1, 0, 0);
setLayout(layout);
}

void MyWidget::setText(QString text) {
label1->setText(text);
}

wysota
24th March 2011, 01:13
In line #7 of your last snippet you are creating a local variable "label1" which shadows the class member variable "label1" thus the latter remains uninitialized and crashes your program when you try to dereference it.