I had to make my own classes for table view (to implement drag) for model (now it uses a list of MyTableItem
) and header (to handle clicking column)
View:
class DragTableView : public QTableView
{
public:
DragTableView(QWidget *parent = 0);
void Initialzie(Overseer *Overseer);
protected:
void mouseMoveEvent(QMouseEvent *event);
private:
void performDrag();
};
Header:
class ClickableHeaderView : public QHeaderView
{
Q_OBJECT
public:
ClickableHeaderView(ObjectMaster* Master);
~ClickableHeaderView(){};
public slots:
void sectionClicked(int index);
};
Model:
class CustomModelOfCustomObjects : public QAbstractTableModel
{
Q_OBJECT
public:
CustomModelOfCustomObjects();
//(...)
///SOME FUNCTIONS LIKE ADDING ITEM, REMOVING IT, ETC
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool insertRows(int position, int rows, const QModelIndex &index);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
QList <MyTableItem> listOfObjects;
};
MyTableItem
is just a class containing a few QStrings and ints representing data.
I handle mouse click ok, passed info further to my Overseer
class, that stores models (and gives pointer to it to table view) and managed to sort it with this kKeep in mind, this function is Model's functions) :
//Example for sorting by "Name"
void sortItemsBy_Name()
{
qSort(listOfObjects.begin(), listOfObjects.end(), compare_Names);
}
bool compare_Names(MyTableItem &v1, MyTableItem &v2)
{
int result = QString::localeAwareCompare(v1.get_Name() , v2.get_Name());
if(result >0)
return true;
else
return false;
}
It was all good up until this point. List is sorted correctly, but what is displayed - isn't. I tried to use:
emit dataChanged(QModelIndex(), QModelIndex());
It refreshed TableView
's display, but every element was at wrong position, while in list - everything was fine (I checked it in debug).
EDIT 1: Solutions presented in Sorting Qt Table Model - QTableView doesn't get updated didn't do the trick.
EDIT 2:
I noticed that my table view will look exactly the same - if I use layoutAboutToBeChanged
/ dataChanged
/ NOTHING.