这有点丑陋但有效的解决方案。查了源码,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