QWidget :: heightForWidth()不被调用 [英] QWidget::heightForWidth() is not called

查看:1386
本文介绍了QWidget :: heightForWidth()不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的小部件总是有方形的大小。 此答案之后,我已覆盖 QWidget :: heightForWidth() ,我也在@peppe建议的构造函数中调用 setHeightForWidth(true)。大小策略设置为首选(对于横向大小和垂直大小)。

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).

code> heightForWidth()未被调用。

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

这是我的 Widget 类中的heightForWidth()的声明:

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

virtual int heightForWidth(int) const;

这发生在Linux和Windows上。

This happens on Linux and Windows.

推荐答案

您的窗口小部件需要在布局中。

Your widget needs to be in a layout. The below works on both Qt 4 and 5.

在Qt 4中,它只会强制顶层窗口的最小尺寸(如果它在布局中)。

In Qt 4, it will only force the toplevel window's minimum size if it's in a layout.

在Qt 5中,它不强制toplevel窗口大小。可能有一个标志,或者它是一个错误,但我现在不记得。

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();
}

这篇关于QWidget :: heightForWidth()不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆