[SOLVED] QLineEdit_object.setFocus() not working at startup?



  • I'm trying to set the focus on QLineEdit widget at app startup but for some reasons it fails. Calling the method which includes the QLineEdit_object.setFocus() and is bound to a button click, works perfectly. However on startup, it seems like it doesn't execute at all when set to initialize after widget creation.

    Code example:

    @import sys
    import PySide.QtGui as QG
    import PySide.QtCore as QC

    class GG(QG.QMainWindow):
    def init(self):
    super(GG, self).init()
    self.move(0,0)
    self.resize(400,300)
    self.setWindowTitle('Demo')

        self.tabw = QG.QTabWidget()
        self.tab1 = Tab1()
        self.tab2 = Tab2()
    
        self.tabw.addTab(self.tab1, 'Tab1')
        self.tabw.addTab(self.tab2, 'Tab2')
    
        hbox = QG.QHBoxLayout()
        hbox.addWidget(self.tabw)
    
        self.setCentralWidget(self.tabw)
        self.setLayout(hbox)
        self.show()
    

    class Tab1(QG.QWidget):
    def init(self):
    super(Tab1, self).init()

        self.btns()
        self.inputt()
        self.layoutz()
        self.inp.setFocus() # doesn't set the focus on startup ?
        self.show()
    
    def inputt(self):
        self.inp = QG.QLineEdit('', self)
    
    def btns(self):
        self.btn1 = QG.QPushButton('Button1', self)
        self.btn1.clicked.connect(self.focusit) # works just fine
    
    def layoutz(self):
        vbox = QG.QVBoxLayout()   
        vbox.addWidget(self.btn1)
        vbox.addStretch(1)
        vbox.addWidget(self.inp)
        self.setLayout(vbox)
    
    def focusit(self):
        self.inp.setFocus() # works just fine
    

    class Tab2(Tab1):
    def init(self):
    super(Tab2, self).init()

    def main():
    app = QG.QApplication(sys.argv)
    a = GG()
    sys.exit(app.exec_())

    if name == 'main':
    main()@


  • Moderators

    Hi, welcome to devnet

    AFAIK you can't set focus to a widget that is not visible. Try to show it first.



  • I managed to set the focus properly from QMainWindow widget by:

    @self.tab2.inp.setFocus()
    self.tab1.inp.setFocus()@

    For some reason the order of calling setFocus() matters and only works if is reversed to creation order.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.