我正在嘗試根據用戶在組合框中選擇的內容來更改 QLabel 中的文本,我要設定的文本__repr__是該類的函式。這是我用來嘗試做我想做的事情的代碼:
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
我得到的錯誤是TypeError: setText(self, str): argument 1 has unexpected type 'type'. 我有點明白我使用錯誤的資訊將 QLabel 設定為,但我不知道該怎么做。
uj5u.com熱心網友回復:
錯誤很少。
object是 Python 中的特殊物件/類,您不應將其用作變數。您使用
setText(object)in__init__但您從不將文本分配給變數object您應該使用
self.inself.m_label在其他功能中訪問此小部件。在其他功能中,您必須使用
setText(..)來更改標簽中的文本。您不能通過將新文本分配給變數來更改它object
如果您需要結果,請__repr__使用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
順便說一句:text_changed被執行PyQt但它不知道如何處理回傳值 - 所以使用return object是沒用的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461138.html
