4
\$\begingroup\$

I am learning PySide and am trying to implement widgets within a main window. My goal right now is very simple: I want to place a QLabel, with independently defined event handling, inside a main window that has its own event handling:

# -*- coding: utf-8 -*-
from PySide import QtGui, QtCore

class MainWindow(QtGui.QWidget):
    '''Main window lets user know when window was clicked on non-widget space'''
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.initUI()    
    def initUI(self):
        self.myLabel=TalkingQLabel("Don't mess with Breakfast!", self) 
        self.myLabel.setGeometry(50, 50, 200, 120)       
        self.setGeometry(300,200,300,250)
        self.show()
    def mousePressEvent(self, event):
        print "Well, you pressed in main window!"

class TalkingQLabel(QtGui.QLabel):
    '''QLab el that indicates when it was pressed'''
    def __init__(self, txt, parent):
        QtGui.QLabel.__init__(self, txt, parent)
        self.initUI()
    def initUI(self):
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setStyleSheet("QLabel { color: rgb(255, 255, 0); font-size: 15px; background-color: rgb(0,0,0)}")
    def mousePressEvent(self, event):
        print "This time you pressed in a label"                

def main():
    import sys
    qtApp=QtGui.QApplication(sys.argv)
    myTalker=MainWindow()
    sys.exit(qtApp.exec_())

if __name__=="__main__":
    main()

Was it good practice to have two separate classes like this for Qt programming, or should I have defined TalkingQLabel within MainWindow because they are in a parent-child relationship, and always will be in this application? Is there a standard within the Qt community I should know about, especially in cases when one widget is a child of another?

Related pages:

\$\endgroup\$
3
\$\begingroup\$

While there is no hard and fast rule, it seems to make code more readable and modular (i.e., Pythonic) to have a separate class for something that is effectively a new Qt widget. This is especially true if there is any chance that new widget might be something you want to break out and use in another project.

See the example labelledwidgets.py from Chapter 11 of Summerfield's book.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.