我的所有对话框都出现在屏幕的左上角而不是中心。
让对话框自动正确放置的最佳方法是什么?
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())
}
}
用一个非常简单的消息对话框.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 https://doc.qt.io/qt-5/qml-qtquick-controls2-dialog.html是的后代Popup https://doc.qt.io/qt-5/qml-qtquick-controls2-popup.html其中有x/y https://doc.qt.io/qt-5/qml-qtquick-controls2-popup.html#x-prop- 坐标。
我认为这将是定位它的一个良好的开始。
对您有利:
-
parent.width
- 这应该是你的窗户的宽度
-
width
- 这应该是你的Dialog
s width
parent.height
height
计算正确的位置,你应该没问题。
这样你就可以创建一个新的基类 CenteredDialog.qml
Dialog {
x: (parent.width - width) / 2
y: (parent.height - height) / 2
}
然后使用CenteredDialog
代替Dialog
每时每刻。
进一步地,对于动态实例化你可以声明Component
在文件中,并且仅在实例化时使用component.createObject(parentObject, { property1Name : property1Value, property2Name : property2Value ... })
syntax.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)