pgLab/pglab/PgLabTableViewHelper.h
eelke 8fe5e05f7d fix table inspector showed details of wrong table.
Caused by using a proxy index with a function that needed an index that was mapped to the source.
Fow now mostly fixed by introducing multiple functions with clearer naming and using the correct one
but would prefer when the helper could hide the details of there being two index spaces.
2022-01-17 17:30:53 +01:00

84 lines
2 KiB
C++

#pragma once
#include <QTableWidget>
#include <QSortFilterProxyModel>
#include "PgLabTableView.h"
#include <optional>
class PgDatabaseCatalog;
template <typename TableModel>
class PgLabTableViewHelper {
public:
PgLabTableViewHelper(QWidget * parent)
{
m_tableView = new PgLabTableView(parent);
m_dataModel = new TableModel(parent);
m_sortFilter = new QSortFilterProxyModel(parent);
m_sortFilter->setSourceModel(m_dataModel);
m_tableView->setModel(m_sortFilter);
m_tableView->setSortingEnabled(true);
}
PgLabTableView *tableView() const
{
return m_tableView;
}
TableModel *dataModel() const
{
return m_dataModel;
}
QSortFilterProxyModel *sortFilter() const
{
return m_sortFilter;
}
void setCatalog(std::shared_ptr<PgDatabaseCatalog> cat)
{
m_dataModel->setCatalog(cat);
m_tableView->resizeColumnsToContents();
}
QModelIndex currentSourceIndex() const
{
QModelIndex index = m_tableView->selectionModel()->currentIndex();
if (!index.isValid())
return index;
return m_sortFilter->mapToSource(index);
}
typename TableModel::RowItem rowItemForSourceRow(int row) const
{
return m_dataModel->rowItem(row);
}
typename TableModel::RowItem rowItemForProxyIndex(QModelIndex index)
{
QModelIndex sourceIndex = m_sortFilter->mapToSource(index);
return m_dataModel->rowItem(sourceIndex.row());
}
typename TableModel::RowItem rowItemForProxyRow(int row) const
{
return rowItemForProxyIndex(m_sortFilter->index(row, 0, QModelIndex()));
}
std::optional<typename TableModel::RowItem> currentRowItem() const
{
auto index = currentSourceIndex();
if (!index.isValid())
return {};
return rowItemForSourceRow(index.row());
}
private:
PgLabTableView *m_tableView = nullptr;
TableModel *m_dataModel = nullptr;
QSortFilterProxyModel *m_sortFilter = nullptr;
};