QT学习笔记-31.QTABLEVIEW只显示横格,不显示点击虚框的方法

本文介绍了一种使用QLineDelegate类来实现自定义表格视图中线条绘制的方法。通过继承QStyledItemDelegate并覆盖paint方法,可以精细地控制单元格边界的表现形式。

原文链接http://www.cppblog.com/gaimor/archive/2011/11/25/160980.html

重新风格项代理QStyledItemDelegat


class  QLineDelegate :  public  QStyledItemDelegate
{
    Q_OBJECT
public :
    QLineDelegate(QTableView
*  tableView);
protected :
    
void  paint(QPainter *  painter, const  QStyleOptionViewItem &  option, const  QModelIndex &  index)  const ;
private :
    QPen         pen;
    QTableView
*   view;
};

#include  < QPainter >
#include 
" QLineDelegate.h "

QLineDelegate::QLineDelegate(QTableView
*  tableView)
{
    
int  gridHint  =  tableView -> style() -> styleHint(QStyle::SH_Table_GridLineColor,  new  QStyleOptionViewItemV4());
    QColor gridColor 
=  static_cast < QRgb > (gridHint);
    pen 
=  QPen(gridColor,  0 , tableView -> gridStyle());
    view 
=  tableView;
}

void  QLineDelegate::paint(QPainter *  painter,  const  QStyleOptionViewItem &  option, const  QModelIndex &  index) const
{
    QStyleOptionViewItem itemOption(option);
    
if (itemOption.state  &  QStyle::State_HasFocus)
        itemOption.state 
=  itemOption.state  ^  QStyle::State_HasFocus;
    QStyledItemDelegate::paint(painter,itemOption,index);
    QPen oldPen 
=  painter -> pen();
    painter
-> setPen(pen);
    
// painter->drawLine(option.rect.topRight(),option.rect.bottomRight());
    painter -> drawLine(itemOption.rect.bottomLeft(),itemOption.rect.bottomRight());
    painter
-> setPen(oldPen);
}
### 如何在 Qt QtWidgets.QTableView 中实现可编辑的输入功能 要实现在 `QTableView` 中嵌入可编辑的输入功能,通常需要自定义委托(Delegate)。以下是对这一过程的具体说明和示例代码。 #### 自定义 Delegate 的作用 `QTableView` 是基于 MVC 架构设计的控件,其本身并直接管理数据,而是依赖于 Model 提供的数据源[^2]。为了使表格单元格支持特定类型的编辑器(如输入),可以通过继承 `QStyledItemDelegate` 并重写相关方法来定制行为[^1]。 --- #### 自定义 Delegate 的核心方法 以下是几个关键的方法及其用途: - **`createEditor()`**: 创建用于编辑的部件(如 `QLineEdit` 或 `QSpinBox`)。 - **`setEditorData()`**: 将当前单元格的数据加载到编辑器中。 - **`setModelData()`**: 当用户完成编辑后,将编辑器中的数据保存回模型。 - **`updateEditorGeometry()`**: 调整编辑器的位置和大小以匹配单元格几何形状。 这些方法共同决定了如何在 `QTableView` 中呈现和处理编辑操作[^1]。 --- #### 示例代码:在 QTableView 中添加 QLineEdit 编辑功能 下面是一个完整的 Python 示例,展示如何为 `QTableView` 添加一个支持文本输入的单元格编辑功能: ```python import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import ( QApplication, QMainWindow, QTableView, QLineEdit, QStyledItemDelegate, ) class MyModel(QAbstractTableModel): """自定义数据模型""" def __init__(self, data): super().__init__() self._data = data # 数据存储为二维列表 def rowCount(self, parent=None): return len(self._data) def columnCount(self, parent=None): return len(self._data[0]) if self.rowCount() > 0 else 0 def data(self, index, role=Qt.DisplayRole): if not index.isValid(): return QVariant() row, col = index.row(), index.column() if role == Qt.DisplayRole or role == Qt.EditRole: return str(self._data[row][col]) return QVariant() def setData(self, index, value, role=Qt.EditRole): if role != Qt.EditRole or not index.isValid(): return False row, col = index.row(), index.column() try: self._data[row][col] = value self.dataChanged.emit(index, index, [role]) return True except Exception as e: print(e) return False def flags(self, index): default_flags = super().flags(index) if index.isValid(): return default_flags | Qt.ItemIsEditable return default_flags class LineEditDelegate(QStyledItemDelegate): """自定义代理类,允许使用 QLineEdit 进行编辑""" def createEditor(self, parent, option, index): editor = QLineEdit(parent) # 创建 QLineEdit 编辑器 editor.setFrame(False) # 移除边 return editor def setEditorData(self, editor, index): text = index.model().data(index, Qt.DisplayRole) # 获取当前单元格的数据显示在编辑器中 editor.setText(str(text)) def setModelData(self, editor, model, index): model.setData(index, editor.text(), Qt.EditRole) # 将编辑后的数据存回到模型中 def updateEditorGeometry(self, editor, option, index): editor.setGeometry(option.rect) # 设置编辑器位置与大小 if __name__ == "__main__": app = QApplication(sys.argv) window = QMainWindow() table_view = QTableView() # 初始化测试数据 test_data = [ ["Alice", "Engineer"], ["Bob", "Designer"], ["Charlie", "Manager"] ] # 配置模型和视图 model = MyModel(test_data) delegate = LineEditDelegate() table_view.setModel(model) table_view.setItemDelegate(delegate) # 展示窗口 window.setCentralWidget(table_view) window.setWindowTitle("QTableView with QLineEdit Editor") window.resize(400, 300) window.show() sys.exit(app.exec_()) ``` 此代码片段展示了如何通过自定义 `QStyledItemDelegate` 子类,在 `QTableView` 表格中集成 `QLineEdit` 输入作为编辑工具[^1]。 --- #### 扩展功能:其他类型编辑器的支持 除了 `QLineEdit`,还可以扩展支持更多类型的编辑器,例如 `QComboBox`、`QSpinBox` 等。只需针对同列返回相应的编辑器即可。例如: ```python def createEditor(self, parent, option, index): if index.column() == 1: # 如果是第二列,使用下拉菜单 combo = QComboBox(parent) combo.addItems(["Engineer", "Designer", "Manager"]) return combo else: # 默认情况下仍使用 QLineEdit editor = QLineEdit(parent) editor.setFrame(False) return editor ``` 这种灵活性使得可以根据实际需求自由定制交互体验[^3]。 --- ### 总结 通过自定义 `QStyledItemDelegate` 及其实现的核心方法,可以轻松地向 `QTableView` 中引入各种形式的输入或其他复杂组件。这种方法仅适用于简单的文本输入场景,还能够适应更复杂的业务逻辑需求。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值