我的应用程序有一个带按钮的主窗口,当我单击该按钮时,我使用createComponent
创建一个Window {}
子类并显示它(纯粹在 QML 中(。我正在连接另一台显示器的Macbook上运行该应用程序。
如果我不尝试设置新窗口的.x
或.y
属性,那么无论主窗口是在Macbook的屏幕上还是在连接的显示器上(即新窗口始终显示在与主窗口相同的屏幕上(,它都会显示在主窗口的顶部。但是,如果我确实设置了新窗口的.x
或.y
属性(任何值(,那么无论我的主窗口在哪个屏幕上,新窗口始终显示在 macbook 屏幕上。
如何控制我的新窗口显示在哪个可用屏幕中?与此相关的是,如何准确控制新窗口在屏幕中的位置(例如,如何让新窗口始终出现在右下角(?
编辑:基本代码。RemoteWindow.qml:
Window {
id: myWindow
flags: Qt.Window | Qt.WindowTitleHint | Qt.WindowStaysOnTopHint
| Qt.WindowCloseButtonHint
modality: Qt.NonModal
height: 500
width: 350
// window contents, doesn't matter
}
在我的主窗口中,我有这个函数(remoteControl
是一个保留对远程窗口的引用的属性(:
function showRemoteWindow() {
remoteControl.x = Screen.width - remoteControl.width
remoteControl.y = Screen.height - remoteControl.height
remoteControl.show()
}
同样在我的主窗口中,我有一个按钮,在其onClicked:
事件中,我有以下代码:
if (remoteControl) {
showRemoteWindow()
} else {
var component = Qt.createComponent("RemoteWindow.qml")
if (component.status === Component.Ready) {
remoteControl = component.createObject(parent)
showRemoteWindow() // window appears even without this call,
// but calling this method to also set the initial position
}
}
如果我在showRemoteWindow函数中注释掉.x
和.y
的设置,那么我的RemoteWindow总是出现在与我的主窗口(Macbook屏幕或连接的显示器(相同的屏幕上。但是,如果我不注释这两行(或尝试设置窗口的 x 或 y 位置(,那么无论我的主窗口在哪个屏幕,我的 RemoteWindow始终出现在 macbook 屏幕上。
就像@Blabdouze说的,Qt 5.9 现在有一个Window
的screen
属性。 您可以为其分配Qt.application.screens
数组的一个元素。
如果要在第一个屏幕中显示窗口,可以执行以下操作:
import QtQuick.Window 2.3 // the 2.3 is necessary
Window {
//...
screen: Qt.application.screens[0]
}
将屏幕分配给窗口似乎将其定位在屏幕的中心。 如果要精细控制窗口的位置,可以使用x
和y
而不是screen
。例如,如果要在第一个屏幕的左下角显示一个窗口:
Window {
//...
screen: Qt.application.screens[0] //assigning the window to the screen is not needed, but it makes the x and y binding more readable
x: screen.virtualX
y: screen.virtualY + screen.height - height
}
如果你还没有使用Qt 5.9,你可以从c ++公开屏幕数组,如下所示:
QList<QObject*> screens;
for (QScreen* screen : QGuiApplication::screens())
screens.append(screen);
engine.rootContext()->setContextProperty("screens", QVariant::fromValue(screens));
并使用geometry
/virtualGeometry
而不是virtualX
/virtualY
访问屏幕的几何形状:
x: screens[0].geometry.x