python - 如何将宽度/高度固定到 QGridLayout 中的特定列/行?

标签 python pyqt pyqt5 qgridlayout

对于这个问题,我指的是来自 http://zetcode.com/gui/pyqt5/layout/ 的示例 calculator.py

在示例中使用了 QGridLayout。我想问是否可以为某些特定的列/行定义宽度/高度?

请看图片。 enter image description here 例如。我希望第二列的宽度为 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()

输出:

enter image description here

关于python - 如何将宽度/高度固定到 QGridLayout 中的特定列/行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943676/

相关文章:

python - 使用 Python 检查互联网连接

python - 在 python 中使用//

python - 从其他文件调用 setCentralWidget

python - GUI 在循环时变得无响应

python - Django 反向查找获取最新

python - 分析在 Mod_wsgi 上运行的 Python 脚本

python - 如何正确地将标准输出、日志记录和 tqdm 重定向到 PyQt 小部件中

python - QSlider 和按键事件

python - 如何将 qss 应用于 QCalendarWidget?

python - QLabel setMinimumHeight 在自定义 WordWrap Qt.TextWrapAnywhere PyQt5 之后(完全响应有/没有表情符号)