You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for循环实现PyQt5 QGridLayout布局时控件无法正常显示的问题求助

Fixing QGridLayout Not Displaying When Using For Loops in PyQt5

Got it, let's break down why your QGridLayout isn't working as expected and fix it step by step.

First, Let's Spot the Issues in Your Code

  1. Duplicate Button Instance: Look at your btns list—you accidentally included btn5 twice, which means one of your buttons (btn6) was missing from the list. That's a tiny typo but can cause unexpected behavior.
  2. Broken Loop Logic: Your nested while loops inside the for loop are the main culprit. The first button in the list gets stuck in the while loops, getting added multiple times to the layout, while all subsequent buttons never get processed at all. By the time the loop moves to the second button, your y variable is already at 4, so both while conditions fail, and those buttons never get added to the layout.

Here's the Fixed Code

Let's rewrite the loop logic to be clean and predictable—we'll use the button's index in the list to calculate its row and column in the grid:

import sys
from PyQt5.QtWidgets import QApplication, QPushButton , QWidget , QGridLayout
from PyQt5.QtGui import QIcon

class windowExamlpe(QWidget):
    def __init__(self):
        super().__init__()
        gridlayout = QGridLayout()
        
        # Create all your button instances
        btn1 = QPushButton("click 1", self)
        btn2 = QPushButton("click 2", self)
        btn3 = QPushButton("click 3", self)
        btn4 = QPushButton("click 4", self)
        btn5 = QPushButton("click 5", self)
        btn6 = QPushButton("click 6", self)
        btn7 = QPushButton("click 7", self)
        btn8 = QPushButton("click 8", self)
        
        # Fix the duplicate btn5 typo here
        btns = [btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8]
        
        # Loop through buttons with their index to calculate grid position
        for index, btn in enumerate(btns):
            # Calculate row: each row holds 4 buttons, so integer division gives the row number
            row = index // 4
            # Calculate column: remainder gives the position in the row
            col = index % 4
            gridlayout.addWidget(btn, row, col)
        
        self.setLayout(gridlayout)
        self.setWindowTitle("Fixed Grid Layout")  # Add a title to make it easier to see

app = QApplication(sys.argv)
window = windowExamlpe()
window.show()
app.exec_()

Why This Works

  • Fixed Duplicate Button: We corrected the btns list to include all 8 unique buttons you created.
  • Simplified Grid Positioning: Using enumerate gives us each button's index in the list. With index // 4, we get which row the button should go in (since we want 4 buttons per row). index % 4 gives us the exact column position within that row. This logic ensures each button is added exactly once to the correct spot in the grid.
  • No more nested loops causing weird behavior—this loop is straightforward and easy to debug if you need to adjust the number of buttons per row later.

Run this code, and you'll see all your buttons neatly arranged in a 2x4 grid as expected.

内容的提问来源于stack exchange,提问作者Tiger Lion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:38:09