Your widget needs to be in a layout. The below works on both Qt 4 and 5.
In Qt 4, it will only force the toplevel window's minimum size if it's in a layout.
In Qt 5, it doesn't force the toplevel window size. There may be a flag for that or it's a bug but I don't recall at the moment.
#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QDebug>
#include <QVBoxLayout>
#include <QFrame>
class Widget : public QWidget {
mutable int m_ctr;
public:
Widget(QWidget *parent = 0) : QWidget(parent), m_ctr(0) {
QSizePolicy p(sizePolicy());
p.setHeightForWidth(true);
setSizePolicy(p);
}
int heightForWidth(int width) const {
m_ctr ++;
QApplication::postEvent(const_cast<Widget*>(this), new QEvent(QEvent::UpdateRequest));
return qMax(width*2, 100);
}
QSize sizeHint() const {
return QSize(300, heightForWidth(300));
}
void paintEvent(QPaintEvent *) {
QPainter p(this);
p.drawRect(rect().adjusted(0, 0, -1, -1));
p.drawText(rect(), QString("h4w called %1 times").arg(m_ctr));
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QVBoxLayout * l = new QVBoxLayout(&w);
l->addWidget(new Widget);
QFrame * btm = new QFrame;
btm->setFrameShape(QFrame::Panel);
btm->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
l->addWidget(btm);
w.show();
return a.exec();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…