python - 删除Qlabel中不必要的空白

标签 python pyqt5 qlabel

enter image description here

我希望左侧的标签都具有相同的水平长度,同时文本向左对齐。 它们的垂直尺寸等于相应右侧小部件的垂直尺寸。

右侧的标签占用尽可能少的空间。基本上删除文本周围的缩进。

如下所示。

enter image description here

我有这个代码。

import sys
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout


class Window2(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("About")

        vbox = QVBoxLayout()

        hboxes = list()
        disclaimer = {
            'Text': """
                some text
            """,
            'Longer text': """
                longer text longer text text longer text longer    
            """
        }

        for label, text in disclaimer.items():
            hbox = QHBoxLayout()

            for t in (label, text):
                l = QLabel(t)
                l.setAlignment(Qt.AlignLeft)
                l.setStyleSheet('border-style: solid; border-width: 1px; border-color: black;')
                hbox.addWidget(l)

            vbox.addLayout(hbox)

        self.setLayout(vbox)
        self.show()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main_window = Window2()
    sys.exit(app.exec_())

我似乎无法弄清楚它是如何工作的/什么是边距、缩进、填充、间距、拉伸(stretch)等。请帮助我理解并解决这个问题。

最佳答案

有 2 个错误:

  • 多行字符串会添加空格,因此您有两个选项:使用 strip() 删除它们或手动删除它们,在这种情况下我将使用第二个选项。
  • 不要在 QVBoxLayout 中使用嵌套的 QHBoxLayout,因为它们不会保持对齐,而是使用 QGridLayout。
class Window2(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("About")

        disclaimer = {
            "Text": """some text""",
            "Longer text": """longer text longer text text longer text longer""",
        }

        gridlay = QGridLayout(self)

        for i, (label, text) in enumerate(disclaimer.items()):

            for j, t in enumerate((label, text)):
                l = QLabel(t.strip())
                l.setAlignment(Qt.AlignLeft)
                l.setStyleSheet(
                    "border-style: solid; border-width: 1px; border-color: black;"
                )
                gridlay.addWidget(l, i, j)

        self.show()

enter image description here

关于python - 删除Qlabel中不必要的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578155/

相关文章:

Python Pandas read_csv : can we load STRING to NUMPY in one line?

Python按索引从字符串中删除字符的最佳方法

python - django-租户模式 : Migrate data from shared schema to multi tenant schema

python - 使用pyqt5渐进绘画的正确方法

python-3.x - 在对话框之间切换(QDialog)PyQt5

c++ - QHBoxLayout 中小部件之间的间距

python - 如何在 PyQt5 QLabel(固定大小)中增加/减小字体大小?

python - Dask中GroupBy使用自定义聚合函数构造模式及对应计数函数

python - 在组小部件内添加两个水平对齐的单选按钮

c++ - 使用 QpushButton 切换显示在 QLabel 中的图像