【问题标题】:pyqt5 managing layout with labelspyqt5 使用标签管理布局
【发布时间】:2018-07-25 21:05:17
【问题描述】:

我试图在我的布局中添加几个标签,这些项目需要相邻。

下面的代码使它们保持相邻,但位于布局的中间。我希望这些标签位于顶部。

import sys

from PyQt5.QtWidgets import QWidget, QApplication, QDialog, QGridLayout, QLabel, QLineEdit
from PyQt5.Qt import QHBoxLayout, QWindow, QMainWindow, QVBoxLayout


class Example(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)            
        self.initUI()

    def initUI(self):
        vlayout = QVBoxLayout()
        hlayout = QHBoxLayout()
        widget = QWidget()
        widget.setLayout(hlayout)

        a1 = QLabel('label1')
        a2 = QLabel('label2')
        hlayout.addWidget(a1)
        hlayout.addWidget(a2)
        hlayout.addStretch(2)
        vlayout.addLayout(hlayout)
        vlayout.addStretch(1)

        self.setCentralWidget(widget)

        self.setGeometry(500, 500, 500, 500)
        self.setWindowTitle('Lines')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
#     ex.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt pyqt5 qlayout


    【解决方案1】:

    布局必须在小部件内,但在您的情况下,QVBoxLayout 没有由任何小部件表示。

    这个想法是你有以下结构:

    widget
    └── vlayout
        └── hlayout
            ├── a1
            └── a2
    

    使用该结构,我们有以下内容:

    import sys
    
    from PyQt5 import QtCore, QtWidgets
    
    
    class Example(QtWidgets.QMainWindow):
        def __init__(self, *args, **kwargs):
            super(Example, self).__init__(*args, **kwargs)            
            self.initUI()
    
        def initUI(self):
            widget = QtWidgets.QWidget()
    
            vlayout = QtWidgets.QVBoxLayout(widget)
            hlayout = QtWidgets.QHBoxLayout()
    
            a1 = QtWidgets.QLabel('label1', )
            a2 = QtWidgets.QLabel('label2')
    
            hlayout.addWidget(a1)
            hlayout.addWidget(a2)
            hlayout.addStretch()
            vlayout.addLayout(hlayout)
            vlayout.addStretch()
    
            self.setCentralWidget(widget)
    
            self.setGeometry(500, 500, 500, 500)
            self.setWindowTitle('Lines')
            self.show()
    
    
    if __name__ == '__main__':
    
        app = QtWidgets.QApplication(sys.argv)
        ex = Example()
    #     ex.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 2021-06-10
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多