'''
addWidget(QWidget widget, int row, int column, int rowSpan = 1, int columnSpan = 1,Qt.Alignment alignment):
將控件添加到指定的網(wǎng)格位置,并可指定占用的行數(shù)和列數(shù)以及對齊方式。
設(shè)置間距:
setSpacing(int spacing): 設(shè)置網(wǎng)格布局中單元格之間的間距。
獲取和設(shè)置布局的水平和垂直間距:
horizontalSpacing() 和 setHorizontalSpacing(int spacing)
verticalSpacing() 和 setVerticalSpacing(int spacing)
獲取和設(shè)置行和列的伸展因子:
rowStretch(int row) 和 setRowStretch(int row, int stretch)
columnStretch(int column) 和 setColumnStretch(int column, int stretch)
刪除控件:
removeWidget(QWidget widget): 從布局中移除指定的控件。
獲取布局中的項目數(shù)量:
'''
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtGui import *
class Demo(QWidget):
def __init__(self):
super().__init__()
self.resize(400,400)
grid_layout =QGridLayout()
self.labels = []
for i in range(9):
label = QLabel()
label.setStyleSheet("background-color:red")
self.labels.append(label)
grid_layout.addWidget(label,i//3,i%3)
grid_layout.setSpacing(30)
self.setLayout(grid_layout)
self.timer = QTimer(self)
self.timer.start(500)
self.timer.timeout.connect(self.on_timer)
self.index = 0
def on_timer(self):
for label in self.labels:
label.setStyleSheet("background-color:red")
current_label = self.labels[self.index]
current_label.setStyleSheet("background-color:green")
self.index = (self.index+1)%len(self.labels)
class Window(QWidget):
def __init__(self):
super().__init__()
self.resize(800,600)
self.setWindowTitle("QGridLayout柵格布局")
label1 = QLabel("Label1", styleSheet="background-color:cyan")
label2 = QLabel("Label2", styleSheet="background-color:red")
label3 = QLabel("Label3", styleSheet="background-color:yellow")
label4 = QLabel("Label4", styleSheet="background-color:blue")
label5 = QLabel("Label5", styleSheet="background-color:green")
label6 = QLabel("Label6", styleSheet="background-color:gray")
label7 = QLabel("Label7", styleSheet="background-color:black")
#創(chuàng)建gridlayout
gridlayout = QGridLayout()
#添加控件到布局中
gridlayout.addWidget(label1,0,0)
gridlayout.addWidget(label2,0,1)
gridlayout.addWidget(label3,0,2)
gridlayout.addWidget(label4,1,0)
gridlayout.addWidget(label5,1,1)
gridlayout.addWidget(label6,1,2)
gridlayout.addWidget(label7,3,0)
# gridlayout.setSpacing(50)
# gridlayout.setHorizontalSpacing(50)
# gridlayout.setVerticalSpacing(100)
gridlayout.setColumnStretch(0,2)
gridlayout.setColumnStretch(1,1)
gridlayout.setColumnStretch(2,1)
gridlayout.setRowStretch(0,2)
gridlayout.setRowStretch(1,1)
gridlayout.setRowStretch(2,1)
#給父對象設(shè)置布局器
self.setLayout(gridlayout)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
win = Demo()
win.show()
sys.exit(app.exec())
承擔因您的行為而導致的法律責任,
本站有權(quán)保留或刪除有爭議評論。
參與本評論即表明您已經(jīng)閱讀并接受
上述條款。