如何将键盘焦点带到 PyQt 中的 QTextEdit?

How to bring keyboard focus to QTextEdit in PyQt?

我在我的 PyQt 用户界面中插入了一个简单的 QTextEdit 小部件。当用户想要在该小部件中键入文本时,他必须单击它。我的程序应该能够在某些情况下自动执行此操作,这样用户就可以开始在 QTextEdit 小部件中键入文本,而无需单击它。

我已经有所进展,但问题仍未完全解决。当我的程序调用 focus() 函数时,光标将在最后一行的末尾开始闪烁。但是在键盘上键入不会插入任何文本。

    class myTextField(QPlainTextEdit):

        def __init__(self):
            super(myTextField, self).__init__()
            ...


        def focus(self):
            self.focusInEvent(QFocusEvent( QEvent.FocusIn ))
            # Now the cursor blinks at the end of the last line.
            # But typing on your keyboard doesn't insert any text.
            # You still got to click explicitly onto the widget..

        ...

    ###

非常感谢任何帮助:-)

使用setFocus()方法。

def focus(self):
    self.setFocus()