首页 > 解决方案 > python:如何不断更新QGridLayout中的按钮

问题描述

我正在 PyQT5 上制作一个项目,我需要更改 QGirdLayout 中的按钮数量

我正在使用 PyQT5 为我的应用程序制作 GUI。我向服务器询问我应该显示的按钮数量,然后服务器向我发送带有应该在 QGridLayout 中显示的文件名的数据包。但是每次我尝试更新 QGridLayout 的内容时,它什么都不做

 def DownloadFile(self, LoginHash, PassHash, Filename):
        print("FILE : "+ str(Filename))
    def DisplayFiles(self, data):
        print("Displaying files")
        print(data)
        data = data.split("|")[:len(data.split("|")) - 1]
        buttons = {}
        j, index, prev = 0, 0, 0
        for i in range(0, len(data)):

            if i % 3 == 0:
                j += 1
                index = 0
            index += 1
            buttons[(index, j)] = QPushButton(str(data[prev]))
            prev += 1
            pixmap = QPixmap("./button.png")

            # scriptDir = path.dirname(path.realpath(__file__))
            # self.setWindowIcon(QtGui.QIcon(scriptDir + path.sep + 'button.png'))

            print("SYS : + " + (data[prev - 1])[len(str(data[prev - 1])) - len(".mp3"):])
            if ((data[prev - 1])[len(str(data[prev - 1])) - len(".mp3"):] == ".mp3"):
                buttons[(index, j)].setIcon(QIcon('MP3icon.jpg'))
            elif ((data[prev - 1])[len(str(data[prev - 1])) - len(".png"):] == ".png"):
                buttons[(index, j)].setIcon(QIcon('PNGicon.png'))
            elif ((data[prev - 1])[len(str(data[prev - 1])) - len(".html"):] == ".html"):
                buttons[(index, j)].setIcon(QIcon('HTMLicon.jpg'))
                # buttons[(index, j)].setIconSize()
            buttons[(index, j)].clicked.connect(
                partial(DownloadFile, str(window.LoginHash), str(window.PassHash), str(data[prev - 1])))
            buttons[(index, j)].setSizePolicy(
                QSizePolicy.Preferred,
                QSizePolicy.Preferred)
            self.gridLayout.addWidget(buttons[(index, j)], index, j)

我希望应用程序更改布局的内容,但它根本不影响它

标签: pythonpyqtpyqt5

解决方案


很难理解你到底想要什么,当我理解正确时,我会这样做。编写一个函数,按照类似的逻辑从网格中删除旧的 QPushButtons。

def delete_old_position(buttons):
    for button in reversed(range(self.gridLayout.count())):
        button_to_remove = self.gridLayout.itemAt(button).widget()
        self.gridLayout.removeWidget(button_to_remove)
        button_to_remove.setParent(None)

之后,您应该能够使用新创建的 QPushButtons 再次填充您的网格。


推荐阅读