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

自定义QFrame中QListWidget无法显示的技术求助

问题解决:自定义Frame中QListWidget无法显示

你的问题核心是:自定义ModMergeFrame中的QListWidget无法显示,但按钮正常显示,且列表项计数返回预期值,将列表移到主窗口中央部件则能正常显示。下面是具体的问题排查和修复方案:

1. 优先检查方法名拼写错误

代码中调用了self.mod_list.additems(["bla", "bla2"]),但PyQt中QListWidget的添加项方法是驼峰命名的addItems(大写I)。如果这不是输入笔误,该错误会导致列表项无法被添加;若你确认count()返回2,说明实际代码中该方法名正确,但仍需再次核对。

2. GridLayout布局冲突(核心问题)

CommonFrame使用了QGridLayout,但ModMergeFrame中添加控件时未指定行/列位置:

self.layout().addWidget(test_button)
self.layout().addWidget(test_button)
self.layout().addWidget(self.mod_list)

QGridLayout默认会把未指定位置的控件都放在(0,0)单元格,后续控件会被前面的覆盖,或布局未为QListWidget分配足够显示空间。

修复方案:

方案一:明确指定控件在GridLayout中的位置

修改ModMergeFrame的初始化代码,为每个控件指定行号,同时设置列表所在行的拉伸因子,让它占满剩余空间:

class ModMergeFrame(CommonFrame):
    def __init__(self, parent, settings):
        super().__init__(parent, settings, objectName="Mod merge")
        test_button = QPushButton(self.objectName(), self)
        # 指定第一行第一列
        self.layout().addWidget(test_button, 0, 0)

        test_button2 = QPushButton("13", self)
        # 指定第二行第一列
        self.layout().addWidget(test_button2, 1, 0)

        self.mod_list = QListWidget(self)
        self.mod_list.addItems(["bla", "bla2"])
        # 指定第三行第一列,设置该行拉伸因子为1,占满剩余空间
        self.layout().addWidget(self.mod_list, 2, 0)
        self.layout().setRowStretch(2, 1)

方案二:改用QVBoxLayout布局

如果不需要网格布局,直接把CommonFrame的布局改成QVBoxLayout,控件会垂直排列,避免覆盖问题:

class CommonFrame(QFrame):
    def __init__(self, parent, settings, objectName):
        super().__init__(parent, objectName=objectName)
        layout = QVBoxLayout(self)  # 替换为QVBoxLayout
        self.setLayout(layout)
        self.hide()
        self.settings = settings

3. 确认show_frame_by_name方法的正确性

确保该方法正确显示目标Frame,示例代码如下:

def show_frame_by_name(self, frame_name):
    # 隐藏所有子Frame
    for child in self.centralWidget().layout().children():
        if isinstance(child, CommonFrame):
            child.hide()
    # 找到并显示指定Frame
    for child in self.centralWidget().layout().children():
        if isinstance(child, CommonFrame) and child.objectName() == frame_name:
            child.show()
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:50:29