对于这个问题,我指的是来自 http://zetcode.com/gui/pyqt5/layout/ 的示例 calculator.py
在示例中使用了 QGridLayout
。我想问是否可以为某些特定的列/行定义宽度/高度?
请看图片。 例如。我希望第二列的宽度为 50px,第三行的高度为 80px。这样无论窗口有多大/多小,这 50px 和 80px 始终按定义显示。其余行/列可以在窗口大小变化时自动缩放。
我已经搜索过但找不到答案。
为方便起见,我将代码粘贴在这里(对原始版本进行了微小的改动)
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout, QPushButton, QApplication)
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Bck', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+']
positions = [(i,j) for i in range(5) for j in range(4)]
for position, name in zip(positions, names):
if name == '':
continue
button = QPushButton(name)
grid.addWidget(button, *position)
self.move(300, 150)
self.setWindowTitle('Calculator')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
最佳答案
一种可能的解决方案是设置小部件的固定尺寸,如下所示:
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Bck', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+']
positions = [(i,j) for i in range(5) for j in range(4)]
for position, name in zip(positions, names):
if name == '':
continue
button = QPushButton(name)
row, column = position
if row == 2:
button.setFixedHeight(80)
if column == 1:
button.setFixedWidth(50)
grid.addWidget(button, *position)
self.move(300, 150)
self.setWindowTitle('Calculator')
self.show()
输出:
关于python - 如何将宽度/高度固定到 QGridLayout 中的特定列/行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943676/