如何刷新QWidget以显示当前信息?



我有一个PySide2 GUI,它在第一页接受来自用户的数字,然后进行一些计算并在第二页显示结果。每个页面都是qstackkedwidget中的一个QWidget。在第二页,即结果页上有一个按钮,可以将用户送回第一页,输入一个新号码。

我的问题是,当我输入一个新数字的结果永远不会改变从第一个数字。我使用print语句来确认结果页面上的标签正在更新,但显示保持不变。

# importing the module
import os
import sys
from PySide2 import QtWidgets
import PySide2.QtUiTools as QtUiTools

class IncomeScreen(QtWidgets.QMainWindow):
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
# Create an instance of DistributionScreen class
self.distribution = DistributionScreen()
# Add DistributionScreen to the stacked widget
widget.addWidget(self.distribution)
# Change index to show DownloadPage
widget.setCurrentIndex(widget.currentIndex()+1)

class DistributionScreen(QtWidgets.QMainWindow):
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(IncomeScreen.init_amount))
print("Initial Amount = {:0.2f}".format(IncomeScreen.init_amount))
# 10 Percent
ten = IncomeScreen.init_amount * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = IncomeScreen.init_amount * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())
# Update widget
self.dialog.update()
# Connect the signals with custom slots
self.dialog.reset_pushButton.clicked.connect(self.reset)
def reset(self):
print("reset")
# Change index to show IncomeScreen
widget.setCurrentIndex(widget.currentIndex()-1)

# main
# if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
income = IncomeScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(income)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")

我也使用Python 3.7.4

编辑:你可以在这里下载ui文件

你的代码有各种各样的问题,但最重要的一个是,每次calculate被调用时,一个新的DistributionScreen添加到堆叠小部件,但widget.setCurrentIndex(widget.currentIndex()+1)将始终去堆叠小部件的第二个索引(这是你创建的第一个实例)

一个可能的简单解决方法是使用addWidget返回的小部件索引或使用setCurrentWidget:

def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
self.distribution = DistributionScreen()
index = widget.addWidget(self.distribution)
widget.setCurrentIndex(index)
# alternatively:
widget.setCurrentWidget(self.distribution)

不幸的是,虽然这将使您的代码工作,但它不是一个有效的解决方案,因为还有其他重要的问题迟早会产生其他问题:

  • 一个堆叠的小部件就像一个标签小部件:它的目的是允许小部件的可重用性;您不应该每次都创建一个新实例,而可以使用现有的实例;
  • 你应该设置或使用依赖于实例的变量的类属性(就像你对IncomeScreen.init_amount所做的那样);
  • 你将QMainWindows添加到一个堆叠的小部件中,这是不鼓励的,因为主窗口应该用作顶层窗口(它有依赖于该方面的功能);注意,甚至QDialog也不是一个有效的候选,您应该选择一个基本的QWidget或容器,如QFrame或QGroupBox;
  • 你正在使用QUiLoader来加载小部件作为主窗口的子窗口,但没有将其添加到布局(或设置为中心小部件),这将使它无法调整自己每当顶层窗口调整大小:如果主窗口变得太小,一些内容将不可见,如果它太大,将有很多未使用的空间;
  • 你试图从实例访问全局变量(widget),而不保证该变量将是有效的;在任何情况下,不应该是创建新部件和设置堆叠部件索引的实例,而应该是堆叠部件本身(或其任何祖先);
  • 最后一个try/except块是非常危险的,因为它阻止你捕获异常(因为它是一个通用的except:)或知道什么是错误的,如果你的程序崩溃;

这可能是您的代码的修订(未经测试,因为您没有提供ui文件)。

import os
import sys
from PySide2 import QtWidgets, QtCore
import PySide2.QtUiTools as QtUiTools

class IncomeScreen(QtWidgets.QWidget):
# a custom signal to notify that we want to show the distribution page
# with the provided value
goToDistribution = QtCore.Signal(float)
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# a proper layout that manages the contents loaded with QUiLoader
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.main)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
self.goToDistribution.emit(float(init_amount))

class DistributionScreen(QtWidgets.QWidget):
reset = QtCore.Signal()
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.dialog)
self.dialog.reset_pushButton.clicked.connect(self.reset)
def setIncome(self, value):
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(value))
print("Initial Amount = {:0.2f}".format(value))
# 10 Percent
ten = value * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = value * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())

class MainWidget(QtWidgets.QStackedWidget):
def __init__(self):
super(MainWidget, self).__init__()
# create *both* the pages here
self.income = IncomeScreen()
self.addWidget(self.income)
self.distribution = DistributionScreen()
self.addWidget(self.distribution)
self.income.goToDistribution.connect(self.goToDistribution)
self.distribution.reset.connect(self.reset)
def goToDistribution(self, value):
# we received the notification signal, then we set the value and 
# show the related page by switching to it
self.distribution.setIncome(value)
self.setCurrentWidget(self.distribution)
def reset(self):
self.setCurrentWidget(self.income)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWidget = MainWidget()
mainWidget.show()
sys.exit(app.exec_())

注意:

  • 如果你想要一个数字控件,你应该使用QSpinBox或QDoubleSpinBox(对于浮点数),或者设置QIntValidator或QDoubleValidator,否则如果用户输入一个非数字值,你的程序将崩溃(由于使用float()没有事先检查字符串是否实际上是一个有效的数字);
  • 虽然QUiLoader很有用,但它的缺点是总是创建一个小部件,所以你永远无法覆盖它的方法;唯一的解决方案是使用pyside-uic生成的文件并使用多重继承方法,或者切换到PyQt并使用其uic.loadUi,它允许在当前小部件上设置UI;
  • 你代码中的大部分问题都是由于最近分享的一些教程(其中一些在youtube上):不幸的是,这些教程建议很多完成,PyQt和Python;我强烈建议您寻找其他资源,最重要的是,始终研究文档。

最新更新