繁体   English   中英

小部件未在 pyqt5 中显示标签

[英]Widget not displaying label in pyqt5

我想在 pyqt5 应用程序中显示一个带有简单消息的窗口。 为此,我创建了一个简单的小部件、一个布局和一个标签。 我将标签添加到布局并将布局分配给小部件,如下所示:

app = QApplication(sys.argv)
# Create a widget to store information
load_widget = QWidget()
# Create a label with the message to display
load_label = QLabel()
# Set label text
load_label.setText('Data being imported, please wait...')
# Create a layout for the widget
load_layout = QVBoxLayout()
# Add label to the layout
load_layout.addWidget(load_label)
# Set layout for the widget
load_widget.setLayout(load_layout)
# Set window title
load_widget.setWindowTitle('Read SD')
# Show the widget
load_widget.show()
sys.exit(app.exec_())

但是,窗口与其标题一起显示,但没有显示标签,如下图所示。

在此处输入图片说明

正如@eyllanesc 所说,这不是 MRE,因为如果复制/粘贴它并运行它,他们会得到:

QWidget: Must construct a QApplication before a QWidget 

我已经扩展了你的代码并正确格式化了它,它工作得很好

from sys import exit as sysExit

from PyQt5.QtCore import *
from PyQt5.QtGui  import *
from PyQt5.QtWidgets import *

# Outline a MainWindow Class using a QWidget
class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

      # Set window title
        self.setWindowTitle('Read SD')

      # Create a label with the message to display
      # And and attach it to the MainWindow 
        self.lblLoad = QLabel()
      # Set label text
        self.lblLoad.setText('Data being imported, please wait...')
      # Create a layout for the widget
        VBox = QVBoxLayout()
      # Add label to the layout
        VBox.addWidget(self.lblLoad)
      # Add Stretch so Label stays at the top
        VBox.addStretch(1)
      # Set layout for the widget
        self.setLayout(VBox)

if __name__ == "__main__":
  # Create Main Thread to Run Program In
    MainThred = QApplication([])
  # Create Main Window from Outlined Class
    MainGUI = MainWindow()
  # Show the Main Window
    MainGUI.show()
  # Launch the Main Thread
    sysExit(MainThred.exec_())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM