恢复QTableView中的垂直滚动

Restoring vertical scroll in QTableView

本文关键字:垂直 滚动 QTableView 恢复      更新时间:2023-10-16

我使用C++、Qt 4.8.7、Visual Studio 2013、Windows 7。我的GUI应用程序包含QTableView。我添加了插槽,用于处理来自我的模型的beginResetModel()reset()信号。这些槽通常被调用,但垂直滚动仍然始终滚动到整个列表的顶部。我该怎么修?我需要恢复当前位置。请注意,在重置期间,不会删除任何行。因此,可以更改旧的行内容和/或添加新行。

//before reset
current_top_row_number_ = table_view_->rowAt(0);
//after reset
table_view_->scrollTo(log_model_->index(current_top_row_number_, 0), QAbstractItemView::PositionAtTop); 

尝试排队呼叫scrollTo,例如

class MyWidget : public MyWidget {
  Q_OBJECT
  int current_top_row_number_;
  QTableView table_view_;
  Q_SLOT void onResetModel() {
    table_view_->scrollTo(log_model_->index(current_top_row_number_, 0),
                          QAbstractItemView::PositionAtTop);
  }
  ...
public:
  MyWidget(QWidget * parent = nullptr) : QWidget{parent} {     
    connect(table_view_, SIGNAL(modelReset()), SLOT(onResetModel(), Qt::QueuedConnection);
  }
};