QWidget.update()或repaint()不会刷新QWidget

时间:2019-07-20 11:51:27

标签: python python-3.x pyqt pyqt5

我正在尝试使用PyQt5在python中创建GUI应用程序,并希望在其中实现启动屏幕。问题在于,在隐藏初始屏幕图像后,我向相同的QWidget添加按钮并调用update(),但未显示。

代码

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget,QPushButton
from PyQt5.QtGui import QCursor,QPixmap
from PyQt5.QtCore import Qt,QTimer

class classer:
   def __init__(self):
      self.w=QWidget()
      self.w.setFixedSize(640,480)
      self.w.setWindowTitle("Classer")

   def splashScreen(self):
      img = QLabel(self.w)
      img.setGeometry(0,0,640,480)
      pixmap = QPixmap('SplashScreen.png')
      img.setPixmap(pixmap.scaled(640,480,Qt.KeepAspectRatio))
      self.w.show()
      QTimer.singleShot(2000, img.hide)

   def mainScreen(self):
      btn=QPushButton(self.w)
      btn.setText('Click')
      btn.move(270,228)
      btn.setCursor(QCursor(Qt.PointingHandCursor))
      self.w.update()
      print("reached here!")

   def run(self):
      self.splashScreen()
      self.mainScreen()
      sys.exit(app.exec_())

if __name__ == '__main__':
   app = QApplication([])
   app.setStyleSheet(open('StyleSheet.css').read())
   instance=classer()
   instance.run()

启动画面

enter image description here

隐藏图像并调用.update()后的当前状态

enter image description here

隐藏图像并调用.update()后的所需状态

enter image description here

1 个答案:

答案 0 :(得分:2)

方法update仅适用于可见的小部件(doc),并且QPushButton不可见,因为在创建按钮之前调用了w.show()方法。因此,您这里实际上不需要update

您可以通过移动一些行来实现此目的,如下所示:

   def splashScreen(self):
      img = QLabel(self.w)
      img.setGeometry(0,0,640,480)
      pixmap = QPixmap('background.png')
      img.setPixmap(pixmap.scaled(640,480,Qt.KeepAspectRatio))    
      QTimer.singleShot(2000, img.hide)

   def mainScreen(self):
      btn=QPushButton(self.w)
      btn.setText('Click')
      btn.move(270,228)
      btn.setCursor(QCursor(Qt.PointingHandCursor))

   def run(self):    
      self.mainScreen()   # --> paint the button
      self.splashScreen() # --> paint the img on top layer
      self.w.show()       # --> display the widget

最好将self.w.show()保留在splashScreen之外,整个小部件将不依赖于初始显示(以防每次运行程序时要注释self.splashScreen()节省2秒的时间) (例如)。