Trying to Emulate a virtual Keyboard

So I am trying to make 2 buttons:

  • one of them to press Enter
  • another to press Escape.

The objective is to press the button to replace Confirm action and the Cancel action of the shortcuts with an actual button. For example for a crop operation to Confirm it or Cancel it.

I managed to find how to press Enter but I fear it only does that. So when I press the button I trigger:

def Question_Confirm( self ):
        ki = Krita.instance()
        ad = ki.activeDocument()
        widget = ki.activeWindow().activeView().canvas()
        event = QKeyEvent( QEvent.KeyPress, Qt.Key_Return, Qt.NoModifier )
        QApplication.sendEvent( widget, event )
        self.Wait( ad )

However to press escape things do not really work and somehow it is treated as a Confirm action.

    def Question_Cancel( self ):
        ki = Krita.instance()
        ad = ki.activeDocument()
        widget = ki.activeWindow().activeView().canvas()
        event = QKeyEvent( QEvent.KeyPress, Qt.Key_Escape, Qt.NoModifier )
        QApplication.postEvent( widget, event )
        self.Wait( ad )

What am I doing wrong ? or How do you trigger a key shortcut through code ? to activate a action that does not exist ?

looks like you are sending / posting events to wrorn objects.

from krita import Krita, Qt, QWidget, QEvent, QApplication, QMdiArea, QKeyEvent, QObject

canvas = Krita.instance().activeWindow().activeView().canvas()
print(f'{canvas = }, {type(canvas) = }, {isinstance(canvas, QWidget) = }')

# you need the actual canvas QWidget, to get it some hacks are needed.

window = Krita.instance().activeWindow()
q_window = window.qwindow()
mdi_area = q_window.findChild(QMdiArea)

target_view = window.activeView()
target_q_view = None
for mdi_window, view in zip(mdi_area.subWindowList(), window.views()):
    if view == target_view:
        target_q_view = mdi_window.widget()
        break

target_q_canvas = None
for w in target_q_view.findChildren(QObject):
    if w.inherits('KisCanvasWidgetBase'):
        target_q_canvas = w
        break
        
print(f'{target_q_view = }, {type(target_q_view) = }, {isinstance(target_q_view, QWidget) = }, {target_q_view.objectName() = }, {target_q_view.metaObject().className() = }')
print(f'{target_q_canvas = }, {type(target_q_canvas) = }, {isinstance(target_q_canvas, QWidget) = }, {target_q_canvas.objectName() = }, {target_q_canvas.metaObject().className() = }')

return_event = QKeyEvent(QEvent.KeyPress, Qt.Key_Return, Qt.NoModifier)
QApplication.sendEvent(target_q_canvas, return_event)

/AkiR

I think it is working now. look.
tela_question

Thank you @AkiR you are really amazing