[Tutor] Self and class functions

Steven D'Aprano steve at pearwood.info
Sun Jun 30 04:04:34 CEST 2013


On 30/06/13 08:36, Phil wrote:
> Thank you for reading this.
>
> I'm attempting to access the GUI widgets. The buttonClicked slot does what I want but I'd like to access the widgets outside of the class. My function setLabel doesn't work because self and ui are not known.


What does "doesn't work" mean?

- when you call setLabel, the computer has a Blue Screen Of Death and crashes;

- you get a dialog box on the screen with the error message "The application 'Python' experienced an unexpected problem and must exit";

- the computer locks up and stops responding until you turn the power off and on;

- the application just closes without warning;

- you get a Python stacktrace, starting with the line "Traceback (most recent call last)" and ending with a error message;

- no error is shown, but the label you are trying to set doesn't change;

- your printer suddenly starts printing dozens of pages with the letter "a" in the top left corner;

- something else?


Only you know for sure what "doesn't work" means in this context, so you need to tell us. Please keep that in mind for any future questions. However, in this case I can *guess* what is happening from context, hopefully correctly, so I'll try to answer. See below.


> from mainwindow import Ui_MainWindow
> from PySide import QtCore, QtGui
> from frame import Frame
>
> class DrawTest(QtGui.QMainWindow):
>      def __init__(self, parent=None):
>          super(DrawTest, self).__init__(parent)
>          self.ui = Ui_MainWindow()
>          self.ui.setupUi(self)
>
>      def buttonClicked(self):
>          print("clicked")
>          self.ui.pushButton.setText("test")
>          self.ui.label.setText("Testing")
>
>      def setLabel(self):
>          self.ui.label.setText("Bingo")
>
> DrawTest.setLabel(self)
> DrawTest.ui.label.setText("Bingo")
>
> The two lines above don't work, so my question is how do access the setText function? And, what do I do about the self parameter in the setLabel function?


You have created a class called DrawTest, but generally speaking you don't operate on the class directly. First you have to create a specific instance of the class. By analogy, you don't take the general class of "dogs" for a walk in the park, you take a specific dog, say, Rover, for a walk.

So in this case, you will need something like

draw_win = DrawTest()  # you may need to provide a parent window?
draw_win.setLabel()


I don't know enough about QT to tell you whether DrawTest can be a standalone window, or whether it needs a parent. If the above doesn't work, don't make us guess what error you get, copy and paste the complete Python traceback and show us.




-- 
Steven


More information about the Tutor mailing list