You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在从Qt Designer导入的PyQt部件中显示信息

在PyQt5中向QWidget部件添加/显示信息

你提到的<widget class="QWidget" name="current">本身只是一个容器部件,它不像Tkinter的Label那样直接显示文本。要在其中显示信息,你需要在这个QWidget内部添加一个显示类部件(比如QLabel、QTextEdit等),有两种常用方法:

方法1:在Qt Designer中修改UI文件

  1. 打开你的Weather.ui文件,找到名为current的QWidget容器。
  2. 从左侧部件面板拖拽一个QLabel(或其他你需要的显示部件)到这个QWidget内部。
  3. 选中新添加的QLabel,在右侧属性面板设置它的objectName(比如current_info_label)。
  4. 保存UI文件后,回到Python代码中直接通过这个objectName访问并修改内容:
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtWidgets, uic
import sys

class Ui(QtWidgets.QDialog):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('Weather.ui', self)
        # 直接访问Designer中添加的Label并设置文本
        self.current_info_label.setText("当前温度:25℃")
        self.show()

app = QApplication([])
window = Ui()
app.exec()

方法2:在Python代码中动态添加部件

如果不想修改UI文件,也可以在代码中直接向current部件添加显示控件:

from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout
from PyQt5 import QtWidgets, uic
import sys

class Ui(QtWidgets.QDialog):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('Weather.ui', self)
        
        # 为current部件创建布局(如果它还没有布局的话)
        layout = QVBoxLayout(self.current)
        # 创建QLabel并设置文本
        info_label = QLabel("当前湿度:60%")
        # 将Label添加到布局中
        layout.addWidget(info_label)
        
        self.show()

app = QApplication([])
window = Ui()
app.exec()

补充说明

  • 你XML中的<attribute name="title">是设置QWidget的窗口标题,但只有当这个QWidget是顶级窗口时才会显示,作为子容器时这个属性不会生效。
  • 除了QLabel,你还可以根据需求使用QTextEdit(多行文本)、QLineEdit(单行输入)等部件,操作方式类似。

内容的提问来源于stack exchange,提问作者Aerospace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:56:02