如何修改QTableWidget编辑状态下单元格的背景色
QTableWidget编辑状态保留单元格背景色与文字颜色的解决方案
我在设计QTableWidget组件时,需要修改单元格编辑状态的默认行为——希望单元格进入编辑模式后,依然保留指定的红色背景与白色文字,而不是默认变为白色背景。当前使用的样式表如下:
QTableWidget{ border:none; border-left:1px solid #b0b9cf; border-bottom: 1px solid #b0b9cf; border-right:1px solid #b0b9cf; selection-color:red; selection-background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 0), stop:1 rgba(255, 255, 255, 0)); } QHeaderView::section:horizontal{ background:#3d4454; color:white; border:0px; border-bottom:2px solid #b0b9cf; boder-left: 1px solid #b0b9cf; border-right:1px solid #b0b9cf; } QTableWidget::item:selected{ border:1px solid blue; } QTableWidget::item:alternate{ background:red; color:white; }
现在的问题是,单元格进入文本编辑模式时,背景会变为白色,需要解决这个问题。
解决方案
问题的核心是单元格进入编辑状态时,Qt默认使用QLineEdit作为编辑器,该编辑器自带白色背景,覆盖了原单元格的样式。可以通过以下两种方式解决:
方式一:给编辑器设置与单元格一致的样式
在现有样式表中添加以下代码,强制编辑器继承单元格的红色背景与白色文字,同时去掉默认边框保持视觉统一:
QTableWidget QLineEdit { background: red; color: white; border: none; }
方式二:让编辑器背景透明,显示下方单元格样式
如果需要适配交替行等动态样式,可设置编辑器背景透明,直接显示下方单元格的原有样式:
QTableWidget QLineEdit { background: transparent; color: white; border: none; }
另外注意:原样式表中QHeaderView::section:horizontal里的boder-left是拼写错误,应改为border-left,避免样式失效。
内容的提问来源于stack exchange,提问作者Mystic_Force
相关产品推荐
相关产品推荐

