Search code examples
pythonkeyboardpysidepyside6

Pyside6 can't write outside the python program


I'm trying to write a code with pyside6 that has 3 buttons and when I press one it will write the symbol

from PySide6.QtWidgets import QApplication, QPushButton,QLineEdit
from PySide6.QtCore import QFile, Qt
from PySide6.QtUiTools import QUiLoader
import keyboard,time

app = QApplication([])

# Assuming the UI file is in the "test" folder
ui_file = QFile("test/ui_file.ui")
ui_file.open(QFile.ReadOnly)
loader = QUiLoader()
window = loader.load(ui_file)
ui_file.close()

# Set the window flag to make it always on top
window.setWindowFlags(window.windowFlags() | Qt.WindowStaysOnTopHint)

pushButton_arrow = window.findChild(QPushButton, "pushButton_arrow")
pushButton_checkmark = window.findChild(QPushButton, "pushButton_checkmark")
pushButton_cross = window.findChild(QPushButton, "pushButton_cross")


def write_1(a):
    keyboard.write(a)

pushButton_arrow.clicked.connect(lambda: write_1("⇒"))
pushButton_cross.clicked.connect(lambda: write_1("✖"))
pushButton_checkmark.clicked.connect(lambda: write_1("✔"))

window.show()

app.exec()

but when I press the button windows will focus on my program and wont write anything (I want it to focus on my writing software the type that thing) I also tried to use alt+tab it works but it's not what I wnat

keyboard.press('alt+tab')  # Switch to the previous active window
keyboard.release('alt+tab')
time.sleep(0.2)

Solution

  • Found a way with pygetwindow

    import pygetwindow as gw
    window_name=""
    def activate_window_1(user_window):
    
        window = gw.getWindowsWithTitle(user_window)[0]
    
        global window_name
        window_name = window.title
    
        window.maximize()
        window.activate()