简体   繁体   English

如何在 PyQt5 Python 中单击按钮时将焦点设置到旧的 window?

[英]How to set focus to the old window on button click in PyQt5 Python?

My Current Project is to create a On Screen Keyboard for my personal usage with my personal functionality.我当前的项目是使用我的个人功能创建一个屏幕键盘供我个人使用。 I made gui and primary function in PyQt5 with Python. I managed to type the letter on button click with pyautogui.write() method.我在 PyQt5 和 Python 中制作了 gui 和主要的 function。我设法使用pyautogui.write()方法在按钮单击时键入字母。 But the problem is, where I want to type there is no focus.但问题是,我想打字的地方没有焦点。 suppose I want to write on chrome's address bar or any other input field on my monitor.假设我想在 chrome 的地址栏或显示器上的任何其他输入字段上书写。 when I click on button to type a letter, chrome lost focus.当我点击按钮输入一个字母时,chrome 失去了焦点。 I want to set focus to the old window while press on any button.我想在按下任何按钮时将焦点设置到旧的 window。 I searched on google about this but didn't found any answer.我在谷歌上搜索了这个但没有找到任何答案。 How can i set focus to old window?如何将焦点设置到旧的 window? or is there any better way to type on focus lost state?或者有没有更好的方法来输入 focus lost state?

You should not try to "set the focus back", as it would be almost impossible to know what window had the focus before (and a new window might raise in the meantime).你不应该试图“把焦点放回去”,因为几乎不可能知道 window 之前有什么焦点(同时可能会增加一个新的 window)。 What you should actually do is to prevent your window to get focus at all, thus avoiding it to steal focus from the others.你实际上应该做的是完全防止你的 window 获得焦点,从而避免它从其他人那里窃取焦点。

In order to achieve this, you must set the appropriate window flag (or initialize the widget with it using the flags keyword argument), which for this is Qt.WindowDoesNotAcceptFocus .为了实现这一点,您必须设置适当的 window标志(或使用flags关键字参数用它初始化小部件),这是Qt.WindowDoesNotAcceptFocus
Note that you might also want to set the Qt.WindowStaysOnTopHint in order to always keep your window above the others:请注意,您可能还想设置Qt.WindowStaysOnTopHint以始终保持您的 window 高于其他:

class MyKeyboard(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(
            QtCore.Qt.WindowDoesNotAcceptFocus
            | QtCore.Qt.WindowStaysOnTopHint
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM