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

QLabel文本过长时QDialog高度不自适应的布局技术问题咨询

解决QDialog无法自动适配QLabel高度的问题

问题描述

已为QDialog设置最小宽度200、最大宽度400且生效,但未设置对话框高度。当QLabel内文本内容过长时,文本无法完全显示,QDialog也未自动增高以适配QLabel的完整内容。

示例代码

#!/usr/bin/env python3
import sys
import this
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.setMinimumWidth(200)
        self.setMaximumWidth(400)

        wdg = QLabel(self)
        wdg.setWordWrap(True)

        # Zen of Python in Rot13
        wdg.setText(this.s.replace('\n', ' ') + " THE END")

        layout = QVBoxLayout(self)
        layout.addWidget(wdg)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    dlg = MyDialog()
    dlg.show()
    sys.exit(app.exec())

解决方案

需要调整QLabel的尺寸策略,同时让QDialog根据布局内容自动调整高度:

  • 给QLabel设置垂直方向的尺寸策略为Expanding,确保布局优先满足QLabel容纳全部文本的高度需求:
    wdg.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
    
  • 在对话框初始化的最后调用adjustSize(),让QDialog根据布局内组件的大小提示计算并调整到合适高度:
    self.adjustSize()
    

修改后的完整代码

#!/usr/bin/env python3
import sys
import this
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.setMinimumWidth(200)
        self.setMaximumWidth(400)

        wdg = QLabel(self)
        wdg.setWordWrap(True)
        # 设置QLabel的垂直尺寸策略为Expanding
        wdg.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)

        # Zen of Python in Rot13
        wdg.setText(this.s.replace('\n', ' ') + " THE END")

        layout = QVBoxLayout(self)
        layout.addWidget(wdg)
        
        # 让对话框自动调整到合适大小
        self.adjustSize()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    dlg = MyDialog()
    dlg.show()
    sys.exit(app.exec())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:05:29