【问题标题】:QQuickWidget Custom Resizing ModeQQuickWidget 自定义大小调整模式
【发布时间】:2021-05-16 05:52:32
【问题描述】:

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

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

【问题讨论】:

    标签: c++ qt qml resize qquickwidget


    【解决方案1】:

    这有点丑陋但有效的解决方案。我检查了QQuickWidgetsource code,发现当ResizeMode无效时,内部updateSize函数什么都不做。

    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
    

    【讨论】:

      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多