c++ - QWidget::heightForWidth() 未被调用

标签 c++ qt

我想让我的小部件始终具有正方形大小。正在关注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 中,它不强制顶层窗口大小。可能有一个标志或它是一个错误,但我现在不记得了。

screenshot

#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/

相关文章:

c++ - Qt:将整个 QScrollArea 内容保存为图像

c++ - 如何在 QT 中获得调整大小 handle ?

c++ - 返回最低节点的名称

c++ - 连接字符串

c++ - pegtl - 如何跳过整个语法的空格

qt - QTcpSocket 以及插槽和信号的运行时错误

使用 Qt 进行 C++0x 编程

Python (PyQt5) 版本的 Qt 标注示例

c++ - 闭合贝塞尔曲线

c++ - 有没有一种标准的方法来记录 GNU Make 包中的依赖关系?