QWidget.setFocus() does not work
-
I have a treeview and a textedit widget:
self.treeview1 = QTreeView() self.textedit1 = MyTextEdit()
where MyTextEdit has only two overridden methods:
class MyTextEdit(QTreeView): def focusInEvent(self, event): ... def focusOutEvent(self, event): ...
Both widgets reside in a splitter:
self.splitview1 = QSplitter() self.splitview1.addWidget(self.treeview1) self.splitview1.addWidget(self.textedit1)
So far, so good.
When I have finished editing the text in QTextEdit, I press a toolbar butten, where I process the modified text and then want to move the focus from QTextEdit to QTreeView:
self.treeview1.setFocus(Qt.OtherFocusReason)
Nothing happens, no error is indicated, the focus remains in QTextEdit.
I tried all other focus reasons as well, to no avail.
I know that setFocus() is a slot and I have not yet fully understood the slot concept.
So, should this work at all?
-
@nst0022 said in QWidget.setFocus() does not work:
class MyTreeView(QTreeView)
I'm confused: don't you mean MyTextEdit here?
Are you sure self.treeview1.setFocus(Qt.OtherFocusReason) is called (you do not show relevant code)? -
@jsulm Yes, sorry, I have updated the original post.
Yes, the code is executed, I had added a print() statement, and I also tried instead sending a keypress event (Shift-Tab) to treeview1:
keypress = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Tab, Qt.ShiftModifier) QGuiApplication.sendEvent(self.treeview1, keypress)
Same result, focus remained in QTextEdit.
-
I guess that @jsulm had answered my questen, whether it should work at all, with a Yes.
So, I have created a minimum python script:
where setFocus() does indeed work.
So, somewhere in my 1900 lines Python script I mess something up, which I have to find now.
-
-
Got it.
In my specific logic, I had set
self.treeview1.setEnabled(False)
but not the corresponding
self.treeview1.setEnabled(True)
At the time I tried to set the focus, the widget was simply disabled.
Now it works.
Detecting this error was hampered by a style sheet I used, that had no entry for
QTreeView:!active
, so, enabled or not, it always looked the same.