如何在 QtQuick Controls 2 的屏幕上居中对话框? [英] How to center dialog on screen in QtQuick Controls 2?
问题描述
我所有的对话框都出现在屏幕的左上角而不是中心.
All my dialogs appear on the top left corner of screen instead of the center.
让对话框自动更正的最佳方法是什么?
What is the best way to let the dialogs be placed automatically correct?
import QtQuick 2.7
import QtQuick.Controls 2.2
ApplicationWindow {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
showMessageBox('Hey this actually works!');
}
function showMessageBox(message) {
var component = Qt.createComponent("MessageDialog.qml")
if(component.status == Component.Ready) {
var dialog = component.createObject(mainWindow)
dialog.title = qsTr("Information")
dialog.text = message
dialog.open()
} else
console.error(component.errorString())
}
}
使用非常简单的MessageDialog.qml:
import QtQuick 2.7
import QtQuick.Controls 2.2
Dialog {
standardButtons: DialogButtonBox.Ok
property alias text : textContainer.text
Text {
id: textContainer
anchors.fill: parent
horizontalAlignment: Qt.AlignLeft
verticalAlignment: Qt.AlignTop
}
}
推荐答案
文档提示,Dialog
是 Popup
具有 x/y
-坐标.
我认为这将是定位它的良好开端.
I think those would be a good start to position it.
对您有用:
parent.width
- 这应该是你的窗口的宽度width
- 这应该是你的Dialog
的宽度parent.height
高度
parent.width
- which should be the width of your windowwidth
- which should be yourDialog
s widthparent.height
height
计算正确的位置,你应该没问题.
Calculate the right positions, and you should be fine.
有了这个你可以创建一个新的基类 CenteredDialog.qml
With this you can create a new base class CenteredDialog.qml
Dialog {
x: (parent.width - width) / 2
y: (parent.height - height) / 2
}
然后一直使用 CenteredDialog
而不是 Dialog
.
and then use CenteredDialog
instead of Dialog
all the time.
此外,对于动态实例化,您可以在文件中声明Component
,并且仅在实例化时使用component.createObject(parentObject, {property1Name : property1Value, property2Name : property2Value ... })
语法.
Further, for dynamic instantiation you might declare the Component
in the file, and only set the properties upon instantiation using the component.createObject(parentObject, { property1Name : property1Value, property2Name : property2Value ... })
syntax.
这篇关于如何在 QtQuick Controls 2 的屏幕上居中对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!