PyQt5嵌入控制台应用焦点问题:键鼠输入无响应
嵌入控制台应用到PyQt5窗口后无法接收键鼠输入的问题
环境:Windows 10系统、Python 3.9 + PyQt5
使用QtGui.QWindow.fromWinId(<window_handle>)函数已成功将VNCviewer、WinSCP等软件嵌入Python GUI,但嵌入控制台应用(如PuTTY SSH会话、命令提示符)时,该窗口无法接收键鼠输入——PyQt窗口始终处于焦点状态,嵌入窗口无法获取焦点。
代码示例
import sys import os import time import pygetwindow from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QGridLayout from PyQt5 import QtGui class MainWindow(QMainWindow): """ Launches the terminal """ def __init__(self, command: str, substring: str): super(MainWindow, self).__init__() widget = QWidget() layout = QGridLayout(widget) self.setCentralWidget(widget) win = latchToWindow(command, substring) hwnd = win._hWnd self.window = QtGui.QWindow.fromWinId(hwnd) self.windowcontainer = self.createWindowContainer(self.window, widget) layout.addWidget(self.windowcontainer, 0, 0) def latchToWindow(winLaunchCommand: str, gettitle: str): """ Used when there are additional dialogs and you need to grab a specific one :param winLaunchCommand: :param title: :return: """ makeNewWindow(winLaunchCommand) while True: windows = pygetwindow.getAllWindows() for win in windows: tempTitle = win.title if gettitle in tempTitle: return win time.sleep(0.1) def makeNewWindow(winLaunchCommand: str): """ Makes a new window with that command, and returns that window :param winLaunchCommand: :return: """ windows = pygetwindow.getAllWindows() os.popen(winLaunchCommand) while True: newWindow = pygetwindow.getAllWindows() if len(newWindow) != len(windows): for win in newWindow: if win.title != "": if win not in windows: time.sleep(0.05) return win if __name__ == '__main__': app = QApplication(sys.argv) app.setStyle("fusion") # 无法响应键鼠输入 form = MainWindow("start cmd.exe", "cmd.exe") # 可以正常响应键鼠输入 # form = MainWindow("putty.exe", "PuTTY") form.setWindowTitle('Embedded Python Terminal') form.show() app.exec()
问题截图

补充说明
已定位问题根源:PyQt5窗口始终占据焦点,需要实现点击嵌入窗口时,让该嵌入窗口获取焦点、PyQt应用暂时失去焦点。尝试过QTBUG-51538中的最后一条评论方案,但无效,求可行解决思路。
内容的提问来源于stack exchange,提问作者KrewTahn
相关产品推荐
相关产品推荐

