在PyQt中添加字典中的按钮

时间:2017-04-02 14:21:16

标签: python dictionary pyqt pyqt4

我正在尝试从字典中制作一堆按钮。在我的情况下必须使用滚动条,因为有超过200个键。我尝试在此链接中使用示例:link。但是,没有成功

这是我的代码:

import sys
import json
import time 
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll =
        QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()


    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
        for item in data.keys():
            button_name = item
            button = QtGui.QPushButton(self.scrollAreaWidgetContents)
            button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

您必须将按钮添加到self.verticalLayoutScroll

self.verticalLayoutScroll.addWidget(button)

完整代码:

import sys
import json
import time 
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()


    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
            for item in data.keys():
                button_name = item
                button = QtGui.QPushButton(self.scrollAreaWidgetContents)
                self.verticalLayoutScroll.addWidget(button)
                button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())

enter image description here