I'm trying to make the text in a QLabel change according to what the user selects in a combobox, the text I want to set being the __repr__
function of the class. Here's the code I'm using to try to do what I want to:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Resonant Orbit Calculator")
self.setMinimumSize(QSize(500, 400))
m_label = QLabel()
m_label.setText(object)
c_box = QComboBox()
c_box.addItems(planet.name for planet in planets_objects)
c_box.addItems(moon.name for moon in moons_objects)
c_box.currentTextChanged.connect(self.text_changed)
layout = QVBoxLayout()
layout.addWidget(m_label)
layout.addWidget(c_box)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def text_changed(self, t):
for element in planets_objects moons_objects:
if element.name == t:
object = element
break
print(object)
return object
And the error I'm getting is TypeError: setText(self, str): argument 1 has unexpected type 'type'
. I kind of get that I'm using the wrong kind of information to set the QLabel as, but I can't figure out how else to do it.
CodePudding user response:
There are few mistakes.
object
is special object/class in Python and you shouldn't use it as variable.you use
setText(object)
in__init__
but you never assign text to variableobject
you should use
self.
inself.m_label
to have access to this widget in other functions.in other functions you have to use
setText(..)
to change text in label. You can't change it by assigning new text to variableobject
If you need result from __repr__
then use repr(...)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Resonant Orbit Calculator")
self.setMinimumSize(QSize(500, 400))
self.m_label = QLabel()
self.m_label.setText('Default text on start')
c_box = QComboBox()
c_box.addItems(planet.name for planet in planets_objects)
c_box.addItems(moon.name for moon in moons_objects)
c_box.currentTextChanged.connect(self.text_changed)
layout = QVBoxLayout()
layout.addWidget(m_label)
layout.addWidget(c_box)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def text_changed(self, selected):
for element in planets_objects moons_objects:
if element.name == selected:
#self.m_label.setText(element)
self.m_label.setText(repr(element))
break
# OR
#return
BTW: text_changed
is executed by PyQt
but it doesn't know what to do with returned value - so using return object
is useless.