I want to put my custom widget into layout and show this in another widget. I can put my widget as a child for second(container) widget and it works OK, but if I put it into layout for second(container) widget, it fails. I've created simple example to describe it.
Header
class MyClass : public QAbstractButton
{
Q_OBJECT
public:
explicit MyClass(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
QSize sizeHint();
QSize minimumSizeHint();
};
Source
#include <QApplication>
#include <QAbstractButton>
#include <QDebug>
#include <QPainter>
#include <QVBoxLayout>
MyClass::MyClass(QWidget *parent) :
QAbstractButton(parent)
{
setGeometry(10,10, 200, 200);
}
void MyClass::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QPen myPen;
myPen.setWidth(5);
painter.drawRect(QRect(QPoint(5, 5), QSize(190, 190)));
}
QSize MyClass::sizeHint() {
qDebug() << "sizeHint";
return QSize(200, 200);
}
#define OK
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget container;
QVBoxLayout layout;
MyClass customWidget;
#ifdef OK
// It works, but I want the same behaviour with layout
customWidget.setParent(&container);
#else
// Doesn't work,
layout.addWidget(&customWidget);
container.setLayout(&layout);
#endif
container.show();
return a.exec();
}
Example summary:
If I use construction like this everything OK:
Qwidget container;
MyQwidget custom(&container);
container.show();
If construction looks like this, nothing happens:
Qwidget container;
MyQwidget custom;
Qlayout layout;
layout.addWidget(custom);
container.addLayout(layout);
container.show();
Is there any proper way to put custom subclassed widget into layout?
I found the answer. I shall to implement sizeHint()
carefully. It was clear C++ mistake, forgot about const
. Proper way to implement it:
QSize MyClass::sizeHint() const { ... }