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

如何实现WxPython中UltimateListCtrl指定列(A、B列)可编辑?

实现UltimateListCtrl指定列可编辑的示例

要让UltimateListCtrl仅允许列"A"和列"B"可编辑,需要先开启控件的编辑功能,再通过事件拦截控制允许编辑的列。以下是修改后的完整代码:

import wx
import wx.lib.agw.ultimatelistctrl as ULC

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((400, 321))
        self.SetTitle("可编辑列示例")

        self.panel_1 = wx.Panel(self, wx.ID_ANY)
        sizer_1 = wx.BoxSizer(wx.VERTICAL)

        # 添加ULC_EDIT_LABELS样式开启编辑功能
        self.list_ctrl_1 = ULC.UltimateListCtrl(
            self.panel_1, 
            wx.ID_ANY,
            agwStyle=ULC.ULC_REPORT | ULC.ULC_VRULES | ULC.ULC_EDIT_LABELS
        )
        self.list_ctrl_1.InsertColumn(0, "A", format=wx.LIST_FORMAT_LEFT, width=-1)
        self.list_ctrl_1.InsertColumn(1, "B", format=wx.LIST_FORMAT_LEFT, width=-1)
        self.list_ctrl_1.InsertColumn(2, "C", format=wx.LIST_FORMAT_LEFT, width=-1)
        sizer_1.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
        
        # 插入测试数据
        index = self.list_ctrl_1.InsertStringItem(0, "1")  
        self.list_ctrl_1.SetStringItem(index, 1,"2")
        self.list_ctrl_1.SetStringItem(index, 2,"3")

        index = self.list_ctrl_1.InsertStringItem(1, "1")  
        self.list_ctrl_1.SetStringItem(index, 1,"2")
        self.list_ctrl_1.SetStringItem(index, 2,"3")
        
        # 绑定编辑开始事件,控制可编辑列
        self.list_ctrl_1.Bind(ULC.EVT_ULC_BEGIN_LABEL_EDIT, self.OnBeginEdit)

        self.panel_1.SetSizer(sizer_1)
        self.Layout()

    def OnBeginEdit(self, event):
        # 获取当前触发编辑的列索引
        col_index = event.GetColumn()
        # 仅允许列0(A)和列1(B)编辑
        if col_index not in (0, 1):
            event.Veto()  # 取消编辑操作
        else:
            event.Skip()  # 允许编辑继续执行

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()

关键说明

  • 开启编辑基础:创建UltimateListCtrl时添加ULC.ULC_EDIT_LABELS样式,这是控件支持编辑的前提
  • 拦截编辑事件:通过绑定EVT_ULC_BEGIN_LABEL_EDIT事件,在编辑开始前判断列索引
  • 控制编辑权限:对非目标列(索引2,列"C")调用event.Veto()阻止编辑,目标列则调用event.Skip()让编辑流程正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:40:27