首页 > 解决方案 > 调整按钮大小,使用循环在 FormLayout 上添加按钮并删除 FormLayout 边框

问题描述

这是MCVE(一个最小的、完整的、可验证的示例)应该立即运行

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFormLayout, QGroupBox,QPushButton, QScrollArea


class Window(QMainWindow):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setWindowTitle('MCVE')

        '''Window Background'''
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.black)
        self.setPalette(p)

        '''Core Layouts'''
        self.mainLayout = QGridLayout()
        self.picLayout = QHBoxLayout()
        self.redditSubs = QVBoxLayout()
        self.downloadBar = QHBoxLayout()
        self.panel = QWidget()
        self.profileInfo = QGridLayout()

        '''redditSubs Layout -----------------------------------------------------'''
        self.formLayout = QFormLayout()
        self.groupBox = QGroupBox()
        labelList = []
        favList = []
        favIcon = QPushButton('Favs')
        favIcon.setToolTip('<i><b>Add to favourites</i></b>')
        subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
                          'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
                          'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
                          'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
                          'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
                          'Cringetopia']
        for i in range(len(subscribedList)):
            labelList.append(QLabel('r/' + subscribedList[i]))
            favList.append(favIcon)
            self.formLayout.addRow(labelList[i], favList[i])
        self.groupBox.setLayout(self.formLayout)
        scroll = QScrollArea()
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidget(self.groupBox)
        scroll.setWidgetResizable(True)
        self.redditSubs.addWidget(scroll)
        self.groupBox.setObjectName('backgroundColor')
        self.groupBox.setStyleSheet('QLabel {color: #707070; font-size: 20px; padding-left: 10px; padding-top: 15px;}'
                                    'QGroupBox#backgroundColor {background-color: rgb(20, 21, 24); border: 1px solid black}'
                                    'QPushButton {text-align:center; font-size: 20px; padding-left: 10px; padding-top: 15px;}')

        '''------------------------------------------------------'''

        '''Nested Layout'''
        self.mainLayout.addLayout(self.profileInfo, 0, 0)
        self.mainLayout.addLayout(self.picLayout, 0, 1)
        self.mainLayout.addLayout(self.redditSubs, 1, 0)
        self.mainLayout.addLayout(self.downloadBar, 1, 1)

        '''Widgets'''
        self.display = QLabel('QHBoxLayout()')
        self.download = QLabel('QHBoxLayout()')
        self.subs = QLabel('QVBoxLayout()')
        self.fileInfo = QLabel('QGridLayout()')

        '''AddWidgets'''
        self.picLayout.addWidget(self.display)
        self.downloadBar.addWidget(self.download)
        self.redditSubs.addWidget(self.subs)
        self.mainLayout.addWidget(self.panel, 0, 0)
        self.profileInfo.addWidget(self.fileInfo, 0, 0)

        '''Stylesheet'''
        self.panel.setStyleSheet("background-color: red;")
        self.display.setStyleSheet('QLabel {color: white;}')
        self.download.setStyleSheet('QLabel {color: white;}')
        '''Initiating  mainLayout '''
        self.window = QWidget()
        self.window.setLayout(self.mainLayout)
        self.setCentralWidget(self.window)


if __name__ == '__main__':
    app = QApplication([])
    w = Window()
    w.showMaximized()
    app.exec_()

问题:

  1. 标签一个接一个地被添加,而不是按钮。我做得favList.append(QPushButton('Favs'))很好,但是这样我就不能添加图标了。
  2. 无法调整按钮大小
  3. 似乎无法删除 formLayout 周围的边框。

补充:图片之前/之后

添加代码:

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton, QScrollArea


class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setWindowTitle("MCVE")

        """Window Background"""
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.darkYellow)
        self.setPalette(p)

        """Core Layouts"""
        self.mainLayout = QGridLayout()
        self.picLayout = QHBoxLayout()
        self.redditSubs = QVBoxLayout()
        self.downloadBar = QHBoxLayout()
        self.profileInfo = QGridLayout()

        """Nested Layout"""
        self.mainLayout.addLayout(self.profileInfo, 0, 0)
        self.mainLayout.addLayout(self.picLayout, 0, 1)
        self.mainLayout.addLayout(self.redditSubs, 1, 0)
        self.mainLayout.addLayout(self.downloadBar, 1, 1)

        """Widgets"""
        self.display = QLabel("QHBoxLayout()")
        self.download = QLabel("QHBoxLayout()")
        self.subs = QLabel("QVBoxLayout()")
        self.fileInfo = QLabel("QGridLayout()")
        self.panel = QWidget()
        self.redditWidget = QWidget()

        '''redditSubs Layout -----------------------------------------------------'''

        lay1 = QVBoxLayout()
        self.redditWidget.setLayout(lay1)

        subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
                          'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
                          'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
                          'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
                          'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
                          'Cringetopia']



        for i in range(len(subscribedList)):
            lay1.addWidget(QLabel('/r' + subscribedList[i]))
            favIcon = QPushButton('Favs')
            favIcon.setFixedSize(40, 40)
            lay1.addWidget(favIcon, alignment=Qt.AlignRight)
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(self.redditWidget)
        lay1.addWidget(scroll) ##
        self.redditWidget.setObjectName('backgroundColor')
        self.redditWidget.setStyleSheet('QLabel {color: #707070; font-size: 15px;}'
                                        'QWidget#backgroundColor {background-color: rgb(20, 21, 24)};'
                                        'QPushButton {text-align:center; font-size: 15px;}')

        self.redditSubs.addWidget(self.redditWidget)

        '''------------------------------------------------------'''

        """AddWidgets"""

        self.picLayout.addWidget(self.display)
        self.downloadBar.addWidget(self.download)
        self.profileInfo.addWidget(self.panel)
        lay = QVBoxLayout(self.panel)
        lay.addWidget(self.fileInfo)

        """Stylesheet"""
        self.panel.setStyleSheet("background-color: red;")

        """Initiating  mainLayout """
        self.window = QWidget()
        self.window.setLayout(self.mainLayout)
        self.setCentralWidget(self.window)


if __name__ == "__main__":
    app = QApplication([])
    w = Window()
    w.showMaximized()
    app.exec_()

按钮与标签不在同一级别,滚动条无法正常工作并显示。'##' 只有在评论时才会运行。

标签: pythonpython-3.xpyqtpyqt5

解决方案


from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton, QScrollArea


class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setWindowTitle("MCVE")

        """Window Background"""
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.darkYellow)
        self.setPalette(p)

        """Core Layouts"""
        self.mainLayout = QGridLayout()
        self.picLayout = QHBoxLayout()
        self.redditSubs = QVBoxLayout()
        self.downloadBar = QHBoxLayout()
        self.profileInfo = QGridLayout()

        """Nested Layout"""
        self.mainLayout.addLayout(self.profileInfo, 0, 0)
        self.mainLayout.addLayout(self.picLayout, 0, 1)
        self.mainLayout.addLayout(self.redditSubs, 1, 0)
        self.mainLayout.addLayout(self.downloadBar, 1, 1)

        """Widgets"""
        self.display = QLabel("QHBoxLayout()")
        self.download = QLabel("QHBoxLayout()")
        self.subs = QLabel("QVBoxLayout()")
        self.fileInfo = QLabel("QGridLayout()")
        self.panel = QWidget()
        self.redditWidget = QWidget()

        '''redditSubs Layout -----------------------------------------------------'''

        lay1 = QGridLayout()
        self.redditWidget.setLayout(lay1)

        subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
                          'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
                          'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
                          'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
                          'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
                          'Cringetopia']



        for i in range(len(subscribedList)):
            lay1.addWidget(QLabel('/r' + subscribedList[i]),i,0)
            favIcon = QPushButton('Favs')
            favIcon.setFixedSize(40, 40)
            lay1.addWidget(favIcon, i,1)
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(self.redditWidget)
        # lay1.addWidget(scroll)
        self.redditWidget.setObjectName('backgroundColor')
        self.redditWidget.setStyleSheet('QLabel {color: #707070; font-size: 15px;}'
                                        'QWidget#backgroundColor {background-color: rgb(20, 21, 24)};'
                                        'QPushButton {text-align:center; font-size: 15px;}')

        self.redditSubs.addWidget(scroll)

        '''------------------------------------------------------'''

        """AddWidgets"""

        self.picLayout.addWidget(self.display)
        self.downloadBar.addWidget(self.download)
        self.profileInfo.addWidget(self.panel)
        lay = QVBoxLayout(self.panel)
        lay.addWidget(self.fileInfo)

        """Stylesheet"""
        self.panel.setStyleSheet("background-color: red;")

        """Initiating  mainLayout """
        self.window = QWidget()
        self.window.setLayout(self.mainLayout)
        self.setCentralWidget(self.window)


if __name__ == "__main__":
    app = QApplication([])
    w = Window()
    w.showMaximized()
    app.exec_()

正是我想要的方式。


推荐阅读