除了uniformRowHeights
在你QTreeView
这里出发,我会尝试。
QAbstractItemModel
有几种方法可以做到这一点,我喜欢使用 Qt的信号/插槽,因此我们将通过QTreeView
. 此自定义模型将连接到selectionChanged
来自QItemSelectionModel
您的QTreeView
. 示例代码/片段适用于单选模式,但您可以轻松更改它以处理多个选定的行。
第 1 步 - 使用选择槽创建自定义模型
创建派生自的自定义模型类,QAbstractItemModel
并确保您创建了一个插槽,例如:
Q_SLOTS:
void onSelectionChanged( const QItemSelection&, const QItemSelection& );
在您的模型类中添加以下片段/方法。
void MyModelClass::onSelectionChanged( const QItemSelection& selected,
const QItemSelection& deselected )
{
if( !selected.empty() )
{
// Save the index within the class.
m_selectedIndex = selected.first();
Q_EMIT dataChanged( m_selectedIndex, m_selectedIndex );
}
}
QVariant MyModelClass::data( const QModelIndex& index, int role ) const
{
// Use the selected index received from the selection model.
if( m_selectedIndex.isValid() &&
index == m_selectedIndex &&
role == Qt::SizeHintRole )
{
// Return our custom size!
return QSize( 50, 50 );
}
...
}
第 2 步 - 将选择更改连接到您的模型
在您QTreeView
创建自定义模型的初始化中并执行以下操作:
MyTreeView::MyTreeView( QWidget* parent ) : QWidget( parent )
{
...
MyModelClass* model = new MyModelClass();
setModel( model );
setSelectionMode( QAbstractItemView::SingleSelection );
setSelectionBehavior( QAbstractItemView::SelectRows );
connect
(
selectionModel(),
SIGNAL( selectionChanged(const QItemSelection&, const QItemSelection&) ),
model,
SLOT( onSelectionChanged(const QItemSelection&, const QItemSelection&) )
);
}
我确信有几种方法可以做到这一点,即QItemSelectionModel
直接交给你QAbstractItemModel
,但我更喜欢使用信号/插槽并将选择保存在模型中。
希望这可以帮助。