PyQt - Good practice for Qt object references



  • Hi!
    Can anyone tell me which of the following two ways is good practice?

    class Widget(QWidget):
    
        def __init__(self, parent=None):
            QWidget.__init__(self, parent)
            self._label = QLabel("Hi!")
    
        def do(self):
            print(self._label.text())
    
    class Widget(QWidget):
    
        def __init__(self, parent=None):
            QWidget.__init__(self, parent)
            label = QLabel("Hi!")
            label.setObjectName("label")
    
        def do(self):
            label = self.findChild(QWidget, 'label')
            if label not None:
                print(label.text())         
    

    Thanks!


  • Lifetime Qt Champion

    Hi,

    First version, you don't want to call find each and every time you want to do something with an internal object.

    By the way, why not use super rather than call the base class __init__ ?


Log in to reply
 

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