9

I want to make my widget always have square size. Following this answer, I have overridden QWidget::heightForWidth(), and I also call setHeightForWidth(true) in the constructor, as suggested by @peppe. The size policy is set to Preferred,Preferred (for both horizontal size and vertical size).

However, heightForWidth() is not being called. Is there anything I am doing wrong?

This is the declaration of heightForWidth() in my Widget class:

virtual int heightForWidth(int) const;

This happens on Linux and Windows.

4

2 回答 2

2

您的小部件需要在布局中。以下适用于 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();
}
于 2013-09-20T18:06:02.283 回答
1

如果小部件在布局中,要保持正方形,您必须重新实现

bool hasHeightForWidth() const{ return true; }
int heightForWidth(int w) const { return w; }

布局类的功能。

于 2017-07-18T13:08:48.397 回答