c++ - QQuickWidget 自定义大小调整模式
问题描述
注意:这是一个自我回答的问题。过去解决它让我有些头疼,所以我认为值得分享。
我有一个专为高清分辨率(1366x768)设计的 qml 应用程序。它正在使用QtQuick.Layouts
,因此可以适应自定义分辨率。但是将其调整为低于高清分辨率会使它变得松软且毫无意义。我没有QQuickWidget
用最小尺寸限制 's 的大小,因为现在我试图将它们中的多个放在QWidget
. QQuickWidget
当尺寸小于初始尺寸(1366x768)时,我想缩小根项目以适应小部件。问题是QQuickWidget
只提供了两个ResizeMode选项,它们都不适合我的需要。并且不可能停用ResizeMode
。所以我试图禁用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
推荐阅读
- ansible - Ansible Tower:将额外变量从一个工作流模板传递到另一个
- oauth - 在 DocuSign 中使用 JWT 时无法在会话错误中找到 OAuth 发起程序参数 - Servicenow 集成
- gatsby - Gatsby - Prismic 站点在构建时中断
- python - .exe 上的图表与 Spyder 上的图表看起来不一样
- javascript - React.js:如何仅在观看滚动位置后调用函数
- python - 将数据框导入另一个脚本
- python - 如何循环更新图形?
- anylogic - 如何在代理群体中创建代理群体
- javascript - 如何通过 JQuery 修复 CWE 117(不正确的日志输出中和)
- regex - 匹配以某个单词开头且不以空格分隔的每个单词中某个字符的所有实例