QQuickWidget自定义调整大小模式



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

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

这是一个丑陋但有效的解决方案。我检查了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(); }

确保根项目的transformOrigin是TopLeft

transformOrigin: Item.TopLeft

最新更新