python - 为什么 PyQt QGridLayout 不调整大小?

标签 python resize pyqt4 python-3.3 qgridlayout

我正在使用 PyQt 编写简单的计算器。在我的代码中,我使用 QGridLayout 来复合小部件。但有一个问题。我找不到调整小部件大小的方法。我尝试使用 QWidget.resize 和 insertStreach,但它无法像我需要的那样工作。哪个函数可以替代QWidget.resize?

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class Button(QPushButton):
    def __init__(self, text, parent, TextObject):
        super().__init__(text, parent=parent or None)
        self.clicked.connect(TextObject.SLOT_TextInsert('%s' %(text)))

class Text(QLineEdit):
    def __init__(self, parent):
        super().__init__(parent=parent)
        self.show()

    def SLOT_TextInsert(self, text):
        return lambda: self.insert('%s' %(text))

    def SLOT_TextGet(self):
        text = self.text()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    root = QWidget()
    text = Text(root) 
    plus = Button('+', root, text)
    minus = Button('-', root, text)
    multiple = Button('*', root, text)
    divide = Button('/', root, text)
    null = Button('0', root, text)
    dot = Button('.', root, text)
    equal = Button('=', root, text)
    clean = Button('Ce', root, text)

    layout = QGridLayout(root)
    layout.setSpacing(2)
    layout.addWidget(text, 1, 1, 1, 5)
    layout.addWidget(plus, 2, 4)
    layout.addWidget(minus, 2, 5)
    layout.addWidget(multiple, 3, 4)
    layout.addWidget(divide, 3, 5)
    layout.addWidget(clean, 4, 4, 1, 2)
    layout.addWidget(null, 5, 1, 1, 2)
    layout.addWidget(dot, 5, 3)
    layout.addWidget(equal, 5, 4, 1, 2)

    num_list = list()
    row=2; col=1
    for i in range(0,9):
        num_list.append(Button('%s' %(i+1), root, text))
        layout.addWidget(num_list[i], row, col )
        col = col+1
        if i == 2 or i == 5:
            col = 1; row = row+1

    root.resize(10,10)
    root.show()        
    sys.exit(app.exec_())

最佳答案

参见QWidget::sizePolicy :

Button-like widgets set the size policy to specify that they may stretch horizontally, but are fixed vertically.

为了使按钮也可以垂直调整大小,您需要修改按钮的大小策略:

class Button(QPushButton):
    def __init__(self, text, parent, TextObject):
        super().__init__(text, parent=parent or None)
        self.setSizePolicy ( QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.clicked.connect(TextObject.SLOT_TextInsert('%s' %(text)))

关于python - 为什么 PyQt QGridLayout 不调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198134/

相关文章:

python - 在 Mac OS X 10.9 上使用 pip 安装 Python 图像库时出错

java - 如何在 JavaFX 中的 SplitPane Divider 上检测鼠标拖动事件

python - PyQt : How to expand all children in a QTreeWidget

python - 文本编辑+组合框+pyqt4

python - 保存上传的 Base64 数据会出现 TypeError : a bytes-like object is required, 而不是 'str'

python - 需要将所有文本转换为纯文本/ASCII(我认为?)

javascript - 当用户调整窗口大小时,如何让我的内容保持移动?

webkit - 发送自定义 header 和 qtwebkit 请求

python - 如何根据连续数据的存在来绘制线条

ios - 使用自动布局设置动态 UIView 以匹配容器 View