首页 > 解决方案 > QQuickWidget 自定义大小调整模式

问题描述

注意:这是一个自我回答的问题。过去解决它让我有些头疼,所以我认为值得分享。

我有一个专为高清分辨率(1366x768)设计的 qml 应用程序。它正在使用QtQuick.Layouts,因此可以适应自定义分辨率。但是将其调整为低于高清分辨率会使它变得松软且毫无意义。我没有QQuickWidget用最小尺寸限制 's 的大小,因为现在我试图将它们中的多个放在QWidget. QQuickWidget当尺寸小于初始尺寸(1366x768)时,我想缩小根项目以适应小部件。问题是QQuickWidget只提供了两个ResizeMode选项,它们都不适合我的需要。并且不可能停用ResizeMode。所以我试图禁用ResizeMode并编写一个自定义的。

标签: c++qtqmlresizeqquickwidget

解决方案


这有点丑陋但有效的解决方案。查了源码QQuickWidget发现内部updateSize函数在ResizeMode无效时什么都不做。

CustomQuickWidget(QWidget* parent = nullptr)
    : QQuickWidget(parent) 
{
    //set invalid resize mode for custom resizing
    setResizeMode(static_cast<QQuickWidget::ResizeMode>(-1));
    setSource(QML_SOURCE);
}

void CustomQuickWidget::resizeEvent(QResizeEvent *event) {
    QQuickWidget::resizeEvent(event);

    const int eventWidth = event->size().width();
    const int eventHeight = event->size().height();
    const int initialWidth = initialSize().width();
    const int initialHeight = initialSize().height();

    if (eventWidth >= initialWidth && eventHeight >= initialHeight) {
        // SizeRootObjectToView
        rootObject()->setSize(event->size());
        rootObject()->setScale(1);
    }
    else {
        // Scale down
        const qreal widthScale = qreal(eventWidth) / initialWidth;
        const qreal heightScale = qreal(eventHeight) / initialHeight;

        if (widthScale < heightScale) {
            // stretch height to fill
            rootObject()->setWidth(initialWidth);
            rootObject()->setHeight(qMin(int(eventHeight / widthScale), maximumHeight()));
            rootObject()->setScale(widthScale);
        }
        else {
            // stretch width to fill
            rootObject()->setWidth(qMin(int(eventWidth / heightScale), maximumWidth()));
            rootObject()->setHeight(initialHeight);
            rootObject()->setScale(heightScale);
        }
    }
}

QSize CustomQuickWidget::sizeHint() const { return initialSize(); }

确保根项目的transformOriginTopLeft.

transformOrigin: Item.TopLeft

推荐阅读