python:如何不断更新QGridLayout中的按钮

问题描述 投票:0回答:2

我正在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)

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

python pyqt pyqt5
2个回答
0
投票

很难理解您到底想要什么,这是我正确理解后的处理方式。编写一个函数,该函数遵循类似的逻辑从网格中删除旧的QPushButton。

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填充网格。


0
投票

您想做什么可能看起来像这样:

© www.soinside.com 2019 - 2024. All rights reserved.