我正在用python开发第一个GUI项目,构建了一个简单的GUI计算器。与其一一对应地创建每个按钮,我不希望使用两个for循环来创建它们。从此列表列表开始:
all_rows = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['0']]
我当前的目标是将这些按钮设置成网格状,我试图按以下方法解决它,但我无法弄清错误:
class MyWindow (QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
#creating default width and height to work with a grid
default_width = 50
default_height = 50
self.setGeometry(0, 0, 10*default_width, 10*default_height)
self.setWindowTitle('Calcolatrice')
self.InitUI()
def InitUI (self):
all_rows = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['0']]
bt_list = []
#setting default height and width of buttons
bt_width = 50
bt_height = 50
#looping troughout all_rows to create buttons
for row in all_rows:
for button in range(len(row)):
#creating each button and giving it the name
bt_list.append(QtW.QPushButton(self))
bt_list[button].setText(row[button])
bt_list[button].setGeometry(0,0,bt_width,bt_height)
#setting button placement
bt_list[button].move(bt_width * button, bt_height * all_rows.index(row))
我显然没想到会有这个输出,我不明白为什么只有8,9和0处于正确的位置
Qt主窗口框架https://doc.qt.io/qt-5/qmainwindow.html#qt-main-window-framework
QMainWindow具有自己的布局
不支持创建没有中央窗口小部件的主窗口。您必须有一个中央小部件,即使它只是一个占位符。
尝试:
import sys
from functools import partial
from PyQt5.Qt import *
class PushButton(QPushButton):
def __init__(self, text, parent=None):
super(PushButton, self).__init__(text, parent)
self.setText(text)
self.setMinimumSize(QSize(50, 50))
self.setMaximumSize(QSize(50, 50))
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.rows = 4
self.columns = 3
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.label = QLabel(self, alignment=Qt.AlignRight)
self.label.setFont(QFont("Times", 12, QFont.Bold))
self.layout = QGridLayout(centralWidget)
self.layout.addWidget(self.label, 0, 0, 1, 3)
_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
len_list = len(_list)
i = 0
for row in range(self.rows):
for column in range(self.columns):
button = PushButton(f'{_list[i]}', self)
button.clicked.connect(partial(self.onClicked, _list[i]))
self.layout.addWidget(button, row+1, column)
i += 1
if i == len_list: break
def onClicked(self, i):
self.label.setNum(i)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindow()
w.setWindowTitle('Calcolatrice')
w.show()
sys.exit(app.exec_())