我想让我的小部件总是有方形尺寸.根据这个答案,我已经覆盖了QWidget::heightForWidth(),我也setHeightForWidth(true)按照@peppe的建议调用了构造函数.大小策略设置为Preferred,Preferred(水平大小和垂直大小).
但是,heightForWidth()没有被召唤.有什么我做错了吗?
这是我Widget班级中heightForWidth()的声明:
virtual int heightForWidth(int) const;
Run Code Online (Sandbox Code Playgroud)
这种情况发生在Linux和Windows上.
您的小部件需要处于布局中。下面的代码适用于 Qt 4 和 5。
在 Qt 4 中,如果顶层窗口位于布局中,它只会强制其最小尺寸。
在 Qt 5 中,它不强制顶级窗口大小。可能有一个标志或者这是一个错误,但我现在不记得了。

#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();
}
Run Code Online (Sandbox Code Playgroud)