我试图在单击按钮时显示一组操作,如果单击另一个按钮则显示其他选项集。 以下是代码:
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions('1')
layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())
单击按钮时,我可以看到值已更新,但未在主布局中更新。 我该如何动态更新小部件? 如果我需要根据动态值添加小部件,我该怎么做呢? 我错过了信号和插槽吗? 如果我错了,请纠正我。感谢
答案 0 :(得分:2)
你的代码几乎就在那里。您看到的问题是小部件正在添加但从未删除。以下代码可以简化,但我试着让它靠近你的代码,这样你就可以更容易地看到变化。
现在主要的变化是有一个类成员screen_layout
,并且在actions()
内添加/删除了小部件。
import sys
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget, QPushButton, QLabel, QApplication
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.screen_layout = layout
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions_full_widget = None
self.actions('1')
# layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
# Remove any previously added widget
if self.actions_full_widget is not None:
self.screen_layout.removeWidget(self.actions_full_widget)
self.actions_full_widget.deleteLater()
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
self.screen_layout.addWidget(self.actions_full_widget)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())