背景
需要在屏幕在居中位置顯示一個對話框,由用戶來進行決策;且此對話框是非模態對話框。

實現方式
1、頂層窗口是一個Window,此窗口設置屏幕居中,透明。
2、對話框設計為Dialog,再將此Dialog掛載在Window上。
這樣,只要Windows可能居中、置頂即可。
結果發現
此對話框並不會置頂顯示,會被其他窗口擋住。
頂層窗口
Window {
id:topWindow
property
int
__hintdlgWidth: 480
property
int
__hintdlgHeight: 320
visible:
true
x: (Screen.width - __hintdlgWidth) / 2
y: (Screen.height - __hintdlgHeight) / 2
width: __hintdlgWidth+20
height: __hintdlgHeight+20
color:
"#00000000"
flags: Qt.FramelessWindowHint | Qt.Window | Qt.WindowStaysOnTopHint
}
|
Qt.WindowStaysOnTopHint
按照官方說法,該屬性僅將最小化的窗口,再次置頂顯示;而不是將一個新創建的窗口直接置頂顯示。
解決方案
方式一:在C++中重置窗口位置
windows:
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
::SetWindowPos((
HWND
)winId(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
Linux:
setWindowFlags(windowFlags() | Qt::BypassWindowManagerHint);
或:
setWindowFlags(windowFlags() | Qt::X11BypassWindowManagerHint);
|
方式二:將創建最小化窗口,后將窗口顯示
activateWindow();
setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
raise
();
//必須加,不然X11會不起作用
#ifdef Q_OS_WIN32 //windows必須加這個,不然windows10 會不起作用,具體參看activateWindow 函數的文檔
HWND
hForgroundWnd = GetForegroundWindow();
DWORD
dwForeID = ::GetWindowThreadProcessId(hForgroundWnd, NULL);
DWORD
dwCurID = ::GetCurrentThreadId();
::AttachThreadInput(dwCurID, dwForeID, TRUE);
::SetForegroundWindow((
HWND
)winId());
::AttachThreadInput(dwCurID, dwForeID, FALSE);
#endif // MAC_OS
|
方式三:在QML中,在必要時再設置Window的風格
//激活窗口
topWindow.requestActivate();
topWindow.
raise
();
//置頂窗口
topWindow.flags |= Qt.WindowStaysOnTopHint
topWindow.show()
topWindow.flags &= ~Qt.WindowStaysOnTopHint
|
