PDA

View Full Version : inherited QPushButton is not being displayed in a layout



seux
20th May 2011, 00:43
Hello,
I want to create a new QPushButton, so I inherited it like this:

class MyButton : public QPushButton
{
Q_OBJECT
public:
MyButton(const QString &text, QWidget *parent = 0);

QPushButton *btn;
};

the code of the constructor looks like this:

MyButton::MyButton(const QString &text, QWidget *parent)
{
btn = new QPushButton(text);
btn->setFlat(true);
//btn->show();
btn->setMaximumHeight(30);
}

When I now add a new MyButton to my MainWindow widget it does not show up, but when I remove the two slashes before btn->show(), the new button is drawn in a separate window. Why does the button only appear in a separate window and not in my main widget?

Here is the code snipped from the main widget:

Btn1 = new MyButton("Hello World");
layout->addWidget(Btn1);

DanH
20th May 2011, 02:42
You are confused about how inheritance works. You shouldn't be creating a new QpushButton.

ChrisW67
20th May 2011, 02:45
MyButton is-a QPushButton: this is not a contains-a relationship. You are setting up an aggregated push button when what you want to be doing is constructing the QPushButton underlying your MyButton object.


class MyButton : public QPushButton
{
Q_OBJECT
public:
MyButton(const QString &text, QWidget *parent = 0);
};

MyButton::MyButton(const QString &text, QWidget *parent): QPushButton(text, parent)
{
setFlat(true);
setMaximumHeight(30);
}

seux
20th May 2011, 15:27
@Chris, I tried your code, but the button does not show up, it seems to be invisible. I created a connection that if the user clicks the button a messagbox appears. And when I click in the empty area the messagebox pops up. But why is my button invisible? I also created a paintEvent which should draw a rectangle around the button


void MyButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);

painter.setPen(Qt::black);

painter.begin(this);

painter.drawRect(this->pos().x(), this->pos().y(), this->pos().x() + this->width(), this->pos().y() + this->height());

painter.end();
}

but there is no rectangular. In the Application Output QtCreator says
QPainter::begin: Painter already active
when the curser is over the button.

stampede
20th May 2011, 16:31
Call base class implementation in paintEvent as well:

void MyButton::paintEvent(QPaintEvent *event)
{
QPushButton::paintEvent(event);
//... your code here
}

Santosh Reddy
20th May 2011, 17:18
This is the correct way to do QPushButton subclassing



class MyButton : public QPushButton
{
Q_OBJECT
public:
MyButton(const QString &text, QWidget *parent = 0);
};

MyButton::MyButton(const QString &text, QWidget *parent) : QPushButton(text, parent)
{
setFlat(true);
setMaximumHeight(30);
}

//main widget code
Btn1 = new MyButton("Hello World");
layout->addWidget(Btn1);