I want to give Focus to a QLineEdit as soon as it appears... in other cases (all Widgets within the same class) it was possible with .setFocus()
- but here this doesn't work.
My candidates are .activateWindow()
and .raise_()
, but I couldn't figure it out how to use them.
edit: My goal is to be able to type into the QLineEdit directly from the keyboard without the need to hit the tab
key or click with the mouse in advance.
Here an example of the relevant parts in question (functional):
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Quiz(QWidget):
def __init__(self):
QWidget.__init__(self)
edit = QLineEdit("Select & Focus")
edit.selectAll()
edit.setFocus() # doesn't work - no effect at all
vbox = QVBoxLayout()
vbox.addWidget(edit)
self.setLayout(vbox)
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
startQuiz = QAction("Start Quiz", self)
startQuiz.triggered.connect(self.startQuizQuestions)
menubar = self.menuBar()
quizMenu = menubar.addMenu("&Quiz")
quizMenu.addAction(startQuiz)
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle("xyz")
self.show()
def startQuizQuestions(self):
newQuiz = Quiz()
self.setCentralWidget(newQuiz)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you're seeing me terribly misusing Python or PyQt4... feel free to criticise, I want to learn.
edit: I found in the PySide Docs for .activateWindow
this discouraging "comment": "On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window." - But I mean it IS the active Window (=MainWindow) it is just an other Widget in the CentralWidget of the active Window. (?)
It works if you give the widget a parent.
Here is the init function of the widget with a new parent argument, used for the QWidget. Then the QWidget is used as parent for the label.
def __init__(self, parent=None):
QWidget.__init__(self, parent)
edit = QLineEdit("Select & Focus", self)
edit.selectAll()
edit.setFocus() # works now
vbox = QVBoxLayout()
vbox.addWidget(edit)
self.setLayout(vbox)
After that you have to pass the MainWindow
as parent to the widget like this:
newQuiz = Quiz(self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With