You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Squish进行Qt Python自动化测试如何获取顶层或活动窗口

Squish for Qt Python脚本获取顶层/活动窗口实现方案

方法1:使用Squish内置API获取顶层窗口(推荐,兼容所有Qt版本)

无需导入Qt相关模块,直接调用Squish自带的应用上下文接口即可获取所有顶层窗口:

from squish import *

# 拿到当前被测应用的上下文
ctx = currentApplicationContext()

# 获取应用所有顶层窗口对象
all_top_windows = ctx.topLevelWindows

# 过滤出当前显示的可见窗口
visible_top_windows = [win for win in all_top_windows if win.visible]

# 遍历打印窗口信息
for win in visible_top_windows:
    print(f"窗口标题:{win.windowTitle}, 类名:{win.className}")

方法2:调用Qt原生API获取活动窗口

如果需要直接获取当前处于激活状态的最靠前窗口,可调用QApplication的activeWindow()接口:

from squish import *
# 根据你的Qt版本调整导入,Qt6对应PyQt6.QtWidgets
from PyQt5.QtWidgets import QApplication

app = QApplication.instance()
active_window = app.activeWindow()

if active_window is not None and active_window.isVisible():
    print(f"当前活动窗口标题:{active_window.windowTitle()}")
    # 关闭窗口可调用close方法
    # active_window.close()

注意:如果被测应用暂时失去系统焦点,activeWindow()可能返回None,此时可遍历方法1得到的可见顶层窗口,按显示顺序取第一个即为最顶层窗口

适配关机场景的处理逻辑

针对你需要关闭所有遮挡弹窗露出主窗口关机按钮的需求,可使用如下执行逻辑:

  • 提前定义主窗口的对象标识符,用于判断当前顶层窗口是否为主窗口
  • 循环关闭非主窗口的顶层弹窗,直到当前顶层窗口为主窗口
  • 强制主窗口置顶保证关机按钮可点击
from squish import *

# 替换为你自己的主窗口对象标识符
main_win = waitForObject(names.Your_Application_Main_Window)

ctx = currentApplicationContext()
while True:
    # 每次重新获取可见顶层窗口
    visible_wins = [win for win in ctx.topLevelWindows if win.visible]
    if not visible_wins:
        break
    # 取最顶层的窗口
    current_top = visible_wins[0]
    if current_top == main_win:
        break
    # 关闭非主窗口的弹窗
    current_top.close()
    snooze(0.5)

# 强制主窗口置顶,避免被系统弹窗遮挡
main_win.raise_()

# 点击关机按钮
clickButton(waitForObject(names.Main_Window_Shutdown_Button))

内容的提问来源于stack exchange,提问作者kwit04ka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:27:05