Why get's Python with PyQt5 slow when creating a large amount of QPushButtons?

此生再无相见时 提交于 2021-01-28 12:10:39

问题


I am building a larger program in PyQt5. I want to create a large number of clickable QPushButtons in a ScrollArea.

As far as I can see it, the program works so far, but gets very slow, when the number of buttons gets high (about 10,000 to 20,000 characters).

How can I ensure that this program builds these buttons responsive? I need to load textfiles separated by chars as QPushButtons which are usually about 15-20 kb large (sometimes up to 50 kb). I believe, this should not be a size limitation.

import sys
from PyQt5.QtWidgets import QApplication, QGridLayout, QScrollArea, QPushButton, QVBoxLayout, QWidget

class Widget(QWidget):

    def __init__(self, parent= None):
        super(Widget, self).__init__()
        self.setFixedHeight(200)
        self.setFixedWidth(1000)
        self.setGeometry(50, 100, 600, 500)

        widget = QWidget()
        layout = QVBoxLayout(self)

        grid = QGridLayout()
        gridpos = [0, 0]
        number = 15000
        for i in range(number):
            btn = QPushButton('x')
            btn.setCheckable(True)
            grid.addWidget(btn, *gridpos)
            gridpos[1] += 1
            if gridpos[1] == 10:
                gridpos[0] += 1
                gridpos[1] = 0
        layout.addLayout(grid)
        widget.setLayout(layout)

        scroll = QScrollArea()
        scroll.setWidgetResizable(False)
        scroll.setWidget(widget)

        vLayout = QVBoxLayout(self)
        vLayout.addWidget(scroll)
        self.setLayout(vLayout)

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

    dialog = Widget()
    dialog.show()

    app.exec_()

回答1:


Apparently, a high amount of qpushbuttons are "expensive" and slow the program down. So, there seems no way to generate 10,000 to 20,000 qpushbuttons at once without delay.

What worked however, was to only show the visible pushbuttons and generate new buttons when they are visible in the window.



来源:https://stackoverflow.com/questions/34127398/why-gets-python-with-pyqt5-slow-when-creating-a-large-amount-of-qpushbuttons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!