我想让我的小部件始终具有正方形大小。正在关注this answer ,我已经覆盖了 QWidget::heightForWidth()
,并且我还在构造函数中调用了 setHeightForWidth(true)
,正如@peppe 所建议的那样。大小策略设置为 Preferred,Preferred
(对于水平大小和垂直大小)。
但是,heightForWidth()
没有被调用。我做错了什么吗?
这是我的 Widget
类中的 heightForWidth() 声明:
virtual int heightForWidth(int) const;
这发生在 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();
}
关于c++ - QWidget::heightForWidth() 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17708449/