简体   繁体   中英

Show custom widget into layout

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?

Side note: your main can be shortened by one line by letting the layout know what widget it acts on, as follows:

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

    QWidget container;
    QVBoxLayout layout(&container);
    MyClass customWidget;
    layout.addWidget(&customWidget);

    container.show();
    return a.exec();
}

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 { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM