为什么PyQt的QGridLayout不自动调整大小?
我正在用PyQt写一个简单的计算器。在我的代码中,我使用QGridLayout来组合各种小部件。但是遇到了一个问题。我找不到调整小部件大小的方法。我试过使用QWidget.resize和insertStretch,但它们的效果并不是我想要的。请问有什么函数可以替代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_())
1 个回答
1
像按钮这样的控件会设置一个大小策略,表示它们可以在水平方向上拉伸,但在垂直方向上是固定的。
如果你想让按钮在垂直方向上也能调整大小,你需要修改按钮的大小策略:
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)))