如何组合布局中的列(colspan功能)

时间:2016-07-12 09:47:49

标签: python qt layout pyqt pyqt5

我有这段代码:

#!/usr/bin/env python3

from PyQt5.QtWidgets import *
import sys    

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QGridLayout()
        self.setLayout(layout)

        label_1 = QLabel("label 1")
        layout.addWidget(label_1, 0, 0)

        label_2 = QLabel("label 2")
        layout.addWidget(label_2, 0, 1)

        label_3 = QLabel("label 3")
        layout.addWidget(label_3, 1, 0)


app = QApplication(sys.argv)

screen = Window()
screen.show()

sys.exit(app.exec_())

我有这个结果:

image example of current code

但我需要这个:

image example of code which I need

我该怎么做?

2 个答案:

答案 0 :(得分:3)

addWidget的第四个和第五个参数允许您指定要跨越的行数和列数:

label_3 = QLabel("label 3")
layout.addWidget(label_3, 1, 0, 1, 2)

答案 1 :(得分:2)

这是QLabel布局的示例代码。它是PyQt4,但您可以尝试使用PyQt5进行小的更改。

import sys
from PyQt4 import QtGui

class Window (QtGui.QWidget):
    def __init__(self, parent=None):        

        super(Window, self).__init__(parent)

        self.verticalLayout     = QtGui.QVBoxLayout (self)
        self.verticalLayout.setObjectName ('verticalLayout')

        self.gridLayout         = QtGui.QGridLayout()
        self.gridLayout.setObjectName ('gridLayout')

        self.label_1 = QtGui.QLabel(self)
        self.label_1.setObjectName('label_1')
        self.label_1.setText ('Label_1')         
        self.label_1.setStyleSheet('background-color: rgb(182, 182, 182);')

        self.label_2 = QtGui.QLabel(self)
        self.label_2.setObjectName('label_2')
        self.label_2.setText ('Label_2')        
        self.label_2.setStyleSheet('background-color: rgb(182, 182, 182);')

        self.label_3 = QtGui.QLabel(self)
        self.label_3.setObjectName('label_3')
        self.label_3.setText ('Label_3')
        self.label_3.setStyleSheet('background-color: rgb(182, 182, 182);')


        self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1)
        self.gridLayout.addWidget(self.label_3, 1, 0, 1, 2)  

        self.verticalLayout.addLayout(self.gridLayout)
        self.resize(300, 100)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())