Qt QTableView - 使用IsUserCheckable时对齐复选框

cwe*_*ton 8 checkbox qt alignment

我正在使用Qt :: ItemIsUserCheckable的 QTableView复选框标志来显示表格单元格中的复选框.

在读取了一些对齐的东西以试图将复选框置于单元格中心之后,我将Qt :: AlignCenter作为TextAlignmentRole从models data()函数返回.

QVariant ExampleModel::data(const QModelIndex &index, int role) const 
{
  if(!index.isValid())
     return QVariant();

  if (role == Qt::TextAlignmentRole) 
       return Qt::AlignCenter | Qt::AlignVCenter;
}
Run Code Online (Sandbox Code Playgroud)

但是这并没有对齐我的复选框.

有谁知道如何对齐复选框是这种模式?

cwe*_*ton 4

在进一步调查委托选项后,我找到了一个很好的参考(不幸的是不再可用),并使用 QItemDelegate 和 IsUserCheckable 提出了以下混合方案。

本质上,您需要扩展 QItemDelegate,并重新实现,使用drawCheck函数居中并使用editorEvent来处理鼠标和键盘事件,同时将模型设置为适当的状态。

void drawCheck(QPainter* painter, QStyleOptionViewItem const& option, QRect const& rect, Qt::CheckState state) const
Run Code Online (Sandbox Code Playgroud)

bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
Run Code Online (Sandbox Code Playgroud)

另请参阅此处类似的问题...