From ccbf341dc8d8e515d9cf918bff7ff9435c477847 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Tue, 24 Dec 2013 11:47:30 +0100 Subject: Initial commit. Basics work. Next: Drag and Drop --- .gitignore | 2 + CMakeLists.txt | 35 +++ CategorizedProxyModel.cpp | 12 + CategorizedProxyModel.h | 18 ++ CategorizedView.cpp | 587 ++++++++++++++++++++++++++++++++++++++++++++++ CategorizedView.h | 96 ++++++++ main.cpp | 53 +++++ 7 files changed, 803 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 CategorizedProxyModel.cpp create mode 100644 CategorizedProxyModel.h create mode 100644 CategorizedView.cpp create mode 100644 CategorizedView.h create mode 100644 main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a5d18fa3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/ +*.user* diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..8a246bcf --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required(VERSION 2.8.9) + +project(GroupView) + +set(CMAKE_AUTOMOC ON) + +IF(APPLE) + message(STATUS "Using APPLE CMAKE_CXX_FLAGS") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall") +ELSEIF(UNIX) + # assume GCC, add C++0x/C++11 stuff + MESSAGE(STATUS "Using UNIX CMAKE_CXX_FLAGS") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall") +ELSEIF(MINGW) + MESSAGE(STATUS "Using MINGW CMAKE_CXX_FLAGS") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11 -Wall") +ENDIF() + +find_package(Qt5Core REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) + +include_directories(${Qt5Core_INCLUDE_DIRS} ${Qt5Gui_INCLUDE_DIRS} ${Qt5Widgets_INCLUDE_DIRS}) + +set(SOURCES + main.cpp + + CategorizedView.h + CategorizedView.cpp + CategorizedProxyModel.h + CategorizedProxyModel.cpp +) + +add_executable(GroupView ${SOURCES}) +qt5_use_modules(GroupView Core Gui Widgets) diff --git a/CategorizedProxyModel.cpp b/CategorizedProxyModel.cpp new file mode 100644 index 00000000..2b54ce1b --- /dev/null +++ b/CategorizedProxyModel.cpp @@ -0,0 +1,12 @@ +#include "CategorizedProxyModel.h" + +#include "CategorizedView.h" + +CategorizedProxyModel::CategorizedProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) +{ +} +bool CategorizedProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const +{ + return left.data(CategorizedView::CategoryRole).toString() < right.data(CategorizedView::CategoryRole).toString(); +} diff --git a/CategorizedProxyModel.h b/CategorizedProxyModel.h new file mode 100644 index 00000000..6e4f3fdc --- /dev/null +++ b/CategorizedProxyModel.h @@ -0,0 +1,18 @@ +#ifndef CATEGORIZEDPROXYMODEL_H +#define CATEGORIZEDPROXYMODEL_H + +#include + +class CategorizedProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + CategorizedProxyModel(QObject *parent = 0); + +protected: + bool lessThan(const QModelIndex &left, const QModelIndex &right) const; +}; + + +#endif // CATEGORIZEDPROXYMODEL_H diff --git a/CategorizedView.cpp b/CategorizedView.cpp new file mode 100644 index 00000000..46b1e072 --- /dev/null +++ b/CategorizedView.cpp @@ -0,0 +1,587 @@ +#include "CategorizedView.h" + +#include +#include +#include +#include +#include + +CategorizedView::Category::Category(const QString &text, CategorizedView *view) + : view(view), text(text), collapsed(false) +{ +} +CategorizedView::Category::Category(const CategorizedView::Category *other) : + view(other->view), text(other->text), collapsed(other->collapsed), iconRect(other->iconRect), textRect(other->textRect) +{ +} + +void CategorizedView::Category::drawHeader(QPainter *painter, const int y) +{ + painter->save(); + + int height = headerHeight() - 4; + int collapseSize = height; + + // the icon + iconRect = QRect(view->m_rightMargin + 2, 2 + y, collapseSize, collapseSize); + painter->setPen(QPen(Qt::black, 1)); + painter->drawRect(iconRect); + static const int margin = 2; + QRect iconSubrect = iconRect.adjusted(margin, margin, -margin, -margin); + int midX = iconSubrect.center().x(); + int midY = iconSubrect.center().y(); + if (collapsed) + { + painter->drawLine(midX, iconSubrect.top(), midX, iconSubrect.bottom()); + } + painter->drawLine(iconSubrect.left(), midY, iconSubrect.right(), midY); + + // the text + int textWidth = painter->fontMetrics().width(text); + textRect = QRect(iconRect.right() + 4, y, textWidth, headerHeight()); + painter->drawText(textRect, text, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter)); + + // the line + painter->drawLine(textRect.right() + 4, y + headerHeight() / 2, view->contentWidth() - view->m_rightMargin, y + headerHeight() / 2); + + painter->restore(); +} + +int CategorizedView::Category::totalHeight() const +{ + return headerHeight() + 5 + contentHeight(); +} +int CategorizedView::Category::headerHeight() const +{ + return qApp->fontMetrics().height() + 4; +} +int CategorizedView::Category::contentHeight() const +{ + if (collapsed) + { + return 0; + } + const int rows = qMax(1, qCeil((qreal)view->numItemsForCategory(this) / (qreal)view->itemsPerRow())); + return view->itemSize().height() * rows; +} +QSize CategorizedView::Category::categoryTotalSize() const +{ + return QSize(view->contentWidth(), contentHeight()); +} + +CategorizedView::CategorizedView(QWidget *parent) + : QListView(parent), m_leftMargin(5), m_rightMargin(5), m_categoryMargin(5)//, m_updatesDisabled(false), m_categoryEditor(0), m_editedCategory(0) +{ + setViewMode(IconMode); + setMovement(Snap); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + setWordWrap(true); +} + +CategorizedView::~CategorizedView() +{ + qDeleteAll(m_categories); + m_categories.clear(); +} + +void CategorizedView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) +{ +// if (m_updatesDisabled) +// { +// return; +// } + + QListView::dataChanged(topLeft, bottomRight, roles); + + if (roles.contains(CategoryRole)) + { + updateGeometries(); + update(); + } +} +void CategorizedView::rowsInserted(const QModelIndex &parent, int start, int end) +{ +// if (m_updatesDisabled) +// { +// return; +// } + + QListView::rowsInserted(parent, start, end); + + updateGeometries(); + update(); +} +void CategorizedView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) +{ +// if (m_updatesDisabled) +// { +// return; +// } + + QListView::rowsAboutToBeRemoved(parent, start, end); + + updateGeometries(); + update(); +} + +void CategorizedView::updateGeometries() +{ + QListView::updateGeometries(); + + m_cachedItemSize = QSize(); + + QMap cats; + + for (int i = 0; i < model()->rowCount(); ++i) + { + const QString category = model()->index(i, 0).data(CategoryRole).toString(); + if (!cats.contains(category)) + { + Category *old = this->category(category); + if (old) + { + cats.insert(category, new Category(old)); + } + else + { + cats.insert(category, new Category(category, this)); + } + } + } + + /*if (m_editedCategory) + { + m_editedCategory = cats[m_editedCategory->text]; + }*/ + + qDeleteAll(m_categories); + m_categories = cats.values(); + + update(); +} + +bool CategorizedView::isIndexHidden(const QModelIndex &index) const +{ + Category *cat = category(index); + if (cat) + { + return cat->collapsed; + } + else + { + return false; + } +} + +CategorizedView::Category *CategorizedView::category(const QModelIndex &index) const +{ + return category(index.data(CategoryRole).toString()); +} +CategorizedView::Category *CategorizedView::category(const QString &cat) const +{ + for (int i = 0; i < m_categories.size(); ++i) + { + if (m_categories.at(i)->text == cat) + { + return m_categories.at(i); + } + } + return 0; +} + +int CategorizedView::numItemsForCategory(const CategorizedView::Category *category) const +{ + return itemsForCategory(category).size(); +} +QList CategorizedView::itemsForCategory(const CategorizedView::Category *category) const +{ + QList indices; + for (int i = 0; i < model()->rowCount(); ++i) + { + if (model()->index(i, 0).data(CategoryRole).toString() == category->text) + { + indices += model()->index(i, 0); + } + } + return indices; +} + +int CategorizedView::categoryTop(const CategorizedView::Category *category) const +{ + int res = 0; + const QList cats = sortedCategories(); + for (int i = 0; i < cats.size(); ++i) + { + if (cats.at(i) == category) + { + break; + } + res += cats.at(i)->totalHeight() + m_categoryMargin; + } + return res; +} + +int CategorizedView::itemsPerRow() const +{ + return qFloor((qreal)contentWidth() / (qreal)itemSize().width()); +} +int CategorizedView::contentWidth() const +{ + return width() - m_leftMargin - m_rightMargin; +} + +bool CategorizedView::lessThanCategoryPointer(const CategorizedView::Category *c1, const CategorizedView::Category *c2) +{ + return c1->text < c2->text; +} +QList CategorizedView::sortedCategories() const +{ + QList out = m_categories; + qSort(out.begin(), out.end(), &CategorizedView::lessThanCategoryPointer); + return out; +} + +QSize CategorizedView::itemSize(const QStyleOptionViewItem &option) const +{ + if (!m_cachedItemSize.isValid()) + { + QModelIndex sample = model()->index(model()->rowCount() -1, 0); + const QAbstractItemDelegate *delegate = itemDelegate(); + if (delegate) + { + m_cachedItemSize = delegate->sizeHint(option, sample); + m_cachedItemSize.setWidth(m_cachedItemSize.width() + 20); + m_cachedItemSize.setHeight(m_cachedItemSize.height() + 20); + } + else + { + m_cachedItemSize = QSize(); + } + } + return m_cachedItemSize; +} + +void CategorizedView::mousePressEvent(QMouseEvent *event) +{ + //endCategoryEditor(); + + if (event->buttons() & Qt::LeftButton) + { + foreach (Category *category, m_categories) + { + if (category->iconRect.contains(event->pos())) + { + category->collapsed = !category->collapsed; + updateGeometries(); + viewport()->update(); + event->accept(); + return; + } + } + + for (int i = 0; i < model()->rowCount(); ++i) + { + QModelIndex index = model()->index(i, 0); + if (visualRect(index).contains(event->pos())) + { + selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); + event->accept(); + return; + } + } + } + + QListView::mousePressEvent(event); +} +void CategorizedView::mouseMoveEvent(QMouseEvent *event) +{ + if (event->buttons() & Qt::LeftButton) + { + for (int i = 0; i < model()->rowCount(); ++i) + { + QModelIndex index = model()->index(i, 0); + if (visualRect(index).contains(event->pos())) + { + selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); + event->accept(); + return; + } + } + } + + QListView::mouseMoveEvent(event); +} +void CategorizedView::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->buttons() & Qt::LeftButton) + { + for (int i = 0; i < model()->rowCount(); ++i) + { + QModelIndex index = model()->index(i, 0); + if (visualRect(index).contains(event->pos())) + { + selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); + event->accept(); + return; + } + } + } + + QListView::mouseReleaseEvent(event); +} +void CategorizedView::mouseDoubleClickEvent(QMouseEvent *event) +{ + /*endCategoryEditor(); + + foreach (Category *category, m_categories) + { + if (category->textRect.contains(event->pos()) && m_categoryEditor == 0) + { + startCategoryEditor(category); + event->accept(); + return; + } + }*/ + + QListView::mouseDoubleClickEvent(event); +} +void CategorizedView::paintEvent(QPaintEvent *event) +{ + QPainter painter(this->viewport()); + + int y = 0; + for (int i = 0; i < m_categories.size(); ++i) + { + Category *category = m_categories.at(i); + category->drawHeader(&painter, y); + y += category->totalHeight() + m_categoryMargin; + } + + for (int i = 0; i < model()->rowCount(); ++i) + { + const QModelIndex index = model()->index(i, 0); + if (isIndexHidden(index)) + { + continue; + } + Qt::ItemFlags flags = index.flags(); + QStyleOptionViewItemV4 option(viewOptions()); + option.rect = visualRect(index); + option.widget = this; + option.features |= wordWrap() ? QStyleOptionViewItemV2::WrapText : QStyleOptionViewItemV2::None; + if (flags & Qt::ItemIsSelectable) + { + option.state |= selectionModel()->isSelected(index) ? QStyle::State_Selected : QStyle::State_None; + } + else + { + option.state &= ~QStyle::State_Selected; + } + option.state |= (index == currentIndex()) ? QStyle::State_HasFocus : QStyle::State_None; + if (!(flags & Qt::ItemIsEnabled)) + { + option.state &= ~QStyle::State_Enabled; + } + itemDelegate()->paint(&painter, option, index); + } +} +void CategorizedView::resizeEvent(QResizeEvent *event) +{ + QListView::resizeEvent(event); + +// if (m_categoryEditor) +// { +// m_categoryEditor->resize(qMax(contentWidth() / 2, m_editedCategory->textRect.width()), m_categoryEditor->height()); +// } + + updateGeometries(); +} + +void CategorizedView::dragEnterEvent(QDragEnterEvent *event) +{ + // TODO +} +void CategorizedView::dragMoveEvent(QDragMoveEvent *event) +{ + // TODO +} +void CategorizedView::dragLeaveEvent(QDragLeaveEvent *event) +{ + // TODO +} +void CategorizedView::dropEvent(QDropEvent *event) +{ + stopAutoScroll(); + setState(NoState); + + if (event->source() != this || !(event->possibleActions() & Qt::MoveAction)) + { + return; + } + + // check that we aren't on a category header and calculate which category we're in + Category *category = 0; + { + int y = 0; + foreach (Category *cat, m_categories) + { + if (event->pos().y() > y && event->pos().y() < (y + cat->headerHeight())) + { + viewport()->update(); + return; + } + y += cat->totalHeight() + m_categoryMargin; + if (event->pos().y() < y) + { + category = cat; + break; + } + } + } + + // calculate the internal column + int internalColumn = -1; + { + const int itemWidth = itemSize().width(); + for (int i = 0, c = 0; + i < contentWidth(); + i += itemWidth, ++c) + { + if (event->pos().x() > (i - itemWidth / 2) && + event->pos().x() < (i + itemWidth / 2)) + { + internalColumn = c; + break; + } + } + if (internalColumn == -1) + { + viewport()->update(); + return; + } + } + + // calculate the internal row + int internalRow = -1; + { + const int itemHeight = itemSize().height(); + const int top = categoryTop(category); + for (int i = top + category->headerHeight(), r = 0; + i < top + category->totalHeight(); + i += itemHeight, ++r) + { + if (event->pos().y() > i && event->pos().y() < (i + itemHeight)) + { + internalRow = r; + break; + } + } + if (internalRow == -1) + { + viewport()->update(); + return; + } + } + + QList indices = itemsForCategory(category); + + // flaten the internalColumn/internalRow to one row + int categoryRow; + { + for (int i = 0; i < internalRow; ++i) + { + if (i == internalRow) + { + break; + } + categoryRow += itemsPerRow(); + } + categoryRow += internalColumn; + } + + int row = indices.at(categoryRow).row(); + if (model()->dropMimeData(event->mimeData(), Qt::MoveAction, row, 0, QModelIndex())) + { + event->setDropAction(Qt::MoveAction); + event->accept(); + } + updateGeometries(); +} + +bool lessThanQModelIndex(const QModelIndex &i1, const QModelIndex &i2) +{ + return i1.data() < i2.data(); +} +QRect CategorizedView::visualRect(const QModelIndex &index) const +{ + if (!index.isValid() || isIndexHidden(index) || index.column() > 0) + { + return QRect(); + } + + const Category *cat = category(index); + QList indices = itemsForCategory(cat); + qSort(indices.begin(), indices.end(), &lessThanQModelIndex); + int x = 0; + int y = 0; + const int perRow = itemsPerRow(); + for (int i = 0; i < indices.size(); ++i) + { + if (indices.at(i) == index) + { + break; + } + ++x; + if (x == perRow) + { + x = 0; + ++y; + } + } + + QSize size = itemSize(); + + QRect out; + out.setTop(categoryTop(cat) + cat->headerHeight() + 5 + y * size.height()); + out.setLeft(x * size.width()); + out.setSize(size); + + return out; +} +/* +void CategorizedView::startCategoryEditor(Category *category) +{ + if (m_categoryEditor != 0) + { + return; + } + m_editedCategory = category; + m_categoryEditor = new QLineEdit(m_editedCategory->text, this); + QRect rect = m_editedCategory->textRect; + rect.setWidth(qMax(contentWidth() / 2, rect.width())); + m_categoryEditor->setGeometry(rect); + m_categoryEditor->show(); + m_categoryEditor->setFocus(); + connect(m_categoryEditor, &QLineEdit::returnPressed, this, &CategorizedView::endCategoryEditor); +} + +void CategorizedView::endCategoryEditor() +{ + if (m_categoryEditor == 0) + { + return; + } + m_editedCategory->text = m_categoryEditor->text(); + m_updatesDisabled = true; + foreach (const QModelIndex &index, itemsForCategory(m_editedCategory)) + { + const_cast(index.model())->setData(index, m_categoryEditor->text(), CategoryRole); + } + m_updatesDisabled = false; + delete m_categoryEditor; + m_categoryEditor = 0; + m_editedCategory = 0; + updateGeometries(); +} +*/ diff --git a/CategorizedView.h b/CategorizedView.h new file mode 100644 index 00000000..1e918496 --- /dev/null +++ b/CategorizedView.h @@ -0,0 +1,96 @@ +#ifndef WIDGET_H +#define WIDGET_H + +#include +#include + +class CategorizedView : public QListView +{ + Q_OBJECT + +public: + CategorizedView(QWidget *parent = 0); + ~CategorizedView(); + + enum + { + CategoryRole = Qt::UserRole + }; + + virtual QRect visualRect(const QModelIndex &index) const; + +protected slots: + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles); + virtual void rowsInserted(const QModelIndex &parent, int start, int end); + virtual void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); + virtual void updateGeometries(); + +protected: + virtual bool isIndexHidden(const QModelIndex &index) const; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *event) override; + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + + void dragEnterEvent(QDragEnterEvent *event) override; + void dragMoveEvent(QDragMoveEvent *event) override; + void dragLeaveEvent(QDragLeaveEvent *event) override; + void dropEvent(QDropEvent *event) override; + +private: + struct Category + { + Category(const QString &text, CategorizedView *view); + Category(const Category *other); + CategorizedView *view; + QString text; + bool collapsed; + QRect iconRect; + QRect textRect; + + void drawHeader(QPainter *painter, const int y); + int totalHeight() const; + int headerHeight() const; + int contentHeight() const; + QSize categoryTotalSize() const; + }; + friend struct Category; + + QList m_categories; + + int m_leftMargin; + int m_rightMargin; + int m_categoryMargin; + int m_itemSpacing; + + //bool m_updatesDisabled; + + Category *category(const QModelIndex &index) const; + Category *category(const QString &cat) const; + int numItemsForCategory(const Category *category) const; + QList itemsForCategory(const Category *category) const; + + int categoryTop(const Category *category) const; + + int itemsPerRow() const; + int contentWidth() const; + + static bool lessThanCategoryPointer(const Category *c1, const Category *c2); + QList sortedCategories() const; + +private: + mutable QSize m_cachedItemSize; + QSize itemSize(const QStyleOptionViewItem &option) const; + QSize itemSize() const { return itemSize(viewOptions()); } + + /*QLineEdit *m_categoryEditor; + Category *m_editedCategory; + void startCategoryEditor(Category *category); + +private slots: + void endCategoryEditor();*/ +}; + +#endif // WIDGET_H diff --git a/main.cpp b/main.cpp new file mode 100644 index 00000000..24d7075e --- /dev/null +++ b/main.cpp @@ -0,0 +1,53 @@ +#include "CategorizedView.h" +#include +#include + +#include "CategorizedProxyModel.h" + +QPixmap icon(const Qt::GlobalColor color) +{ + QPixmap p = QPixmap(32, 32); + p.fill(QColor(color)); + return p; +} +QStandardItem *createItem(const Qt::GlobalColor color, const QString &text, const QString &category) +{ + QStandardItem *item = new QStandardItem; + item->setText(text); + item->setData(icon(color), Qt::DecorationRole); + item->setData(category, CategorizedView::CategoryRole); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); + return item; +} + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + + QStandardItemModel model; + model.setRowCount(10); + model.setColumnCount(1); + + model.setItem(0, createItem(Qt::red, "Red", "Colorful")); + model.setItem(1, createItem(Qt::blue, "Blue", "Colorful")); + model.setItem(2, createItem(Qt::yellow, "Yellow", "Colorful")); + + model.setItem(3, createItem(Qt::black, "Black", "Not Colorful")); + model.setItem(4, createItem(Qt::darkGray, "Dark Gray", "Not Colorful")); + model.setItem(5, createItem(Qt::gray, "Gray", "Not Colorful")); + model.setItem(6, createItem(Qt::lightGray, "Light Gray", "Not Colorful")); + model.setItem(7, createItem(Qt::white, "White", "Not Colorful")); + + model.setItem(8, createItem(Qt::darkGreen, "Dark Green", "")); + model.setItem(9, createItem(Qt::green, "Green", "")); + + CategorizedProxyModel pModel; + pModel.setSourceModel(&model); + + CategorizedView w; + w.setModel(&pModel); + w.resize(640, 480); + w.show(); + + return a.exec(); +} -- cgit From 525f508d94120feae89ee1d1bd960625ab14ed37 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Thu, 26 Dec 2013 21:16:03 +0100 Subject: Loads of stuff, amongst others d&d and many bug fixes --- CategorizedProxyModel.cpp | 11 +- CategorizedView.cpp | 681 +++++++++++++++++++++++++++++++++++----------- CategorizedView.h | 25 ++ 3 files changed, 555 insertions(+), 162 deletions(-) diff --git a/CategorizedProxyModel.cpp b/CategorizedProxyModel.cpp index 2b54ce1b..e4a7563a 100644 --- a/CategorizedProxyModel.cpp +++ b/CategorizedProxyModel.cpp @@ -8,5 +8,14 @@ CategorizedProxyModel::CategorizedProxyModel(QObject *parent) } bool CategorizedProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - return left.data(CategorizedView::CategoryRole).toString() < right.data(CategorizedView::CategoryRole).toString(); + const QString leftCategory = left.data(CategorizedView::CategoryRole).toString(); + const QString rightCategory = right.data(CategorizedView::CategoryRole).toString(); + if (leftCategory == rightCategory) + { + return left.row() < right.row(); + } + else + { + return leftCategory < rightCategory; + } } diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 46b1e072..95505fd7 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -5,6 +5,23 @@ #include #include #include +#include +#include +#include +#include + +template +bool listsIntersect(const QList &l1, const QList t2) +{ + foreach (const T &item, l1) + { + if (t2.contains(item)) + { + return true; + } + } + return false; +} CategorizedView::Category::Category(const QString &text, CategorizedView *view) : view(view), text(text), collapsed(false) @@ -39,7 +56,7 @@ void CategorizedView::Category::drawHeader(QPainter *painter, const int y) // the text int textWidth = painter->fontMetrics().width(text); textRect = QRect(iconRect.right() + 4, y, textWidth, headerHeight()); - painter->drawText(textRect, text, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter)); + view->style()->drawItemText(painter, textRect, Qt::AlignHCenter | Qt::AlignVCenter, view->palette(), true, text); // the line painter->drawLine(textRect.right() + 4, y + headerHeight() / 2, view->contentWidth() - view->m_rightMargin, y + headerHeight() / 2); @@ -77,6 +94,11 @@ CategorizedView::CategorizedView(QWidget *parent) setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); setWordWrap(true); + setDragDropMode(QListView::InternalMove); + setAcceptDrops(true); + + m_cachedCategoryToIndexMapping.setMaxCost(50); + m_cachedVisualRects.setMaxCost(50); } CategorizedView::~CategorizedView() @@ -130,6 +152,8 @@ void CategorizedView::updateGeometries() QListView::updateGeometries(); m_cachedItemSize = QSize(); + m_cachedCategoryToIndexMapping.clear(); + m_cachedVisualRects.clear(); QMap cats; @@ -189,6 +213,17 @@ CategorizedView::Category *CategorizedView::category(const QString &cat) const } return 0; } +CategorizedView::Category *CategorizedView::categoryAt(const QPoint &pos) const +{ + for (int i = 0; i < m_categories.size(); ++i) + { + if (m_categories.at(i)->iconRect.contains(pos)) + { + return m_categories.at(i); + } + } + return 0; +} int CategorizedView::numItemsForCategory(const CategorizedView::Category *category) const { @@ -196,15 +231,47 @@ int CategorizedView::numItemsForCategory(const CategorizedView::Category *catego } QList CategorizedView::itemsForCategory(const CategorizedView::Category *category) const { - QList indices; - for (int i = 0; i < model()->rowCount(); ++i) + if (!m_cachedCategoryToIndexMapping.contains(category)) + { + QList *indices = new QList(); + for (int i = 0; i < model()->rowCount(); ++i) + { + if (model()->index(i, 0).data(CategoryRole).toString() == category->text) + { + indices->append(model()->index(i, 0)); + } + } + m_cachedCategoryToIndexMapping.insert(category, indices, indices->size()); + } + return *m_cachedCategoryToIndexMapping.object(category); +} +QModelIndex CategorizedView::firstItemForCategory(const CategorizedView::Category *category) const +{ + QList indices = itemsForCategory(category); + QModelIndex first; + foreach (const QModelIndex &index, indices) { - if (model()->index(i, 0).data(CategoryRole).toString() == category->text) + if (index.row() < first.row() || !first.isValid()) { - indices += model()->index(i, 0); + first = index; } } - return indices; + + return first; +} +QModelIndex CategorizedView::lastItemForCategory(const CategorizedView::Category *category) const +{ + QList indices = itemsForCategory(category); + QModelIndex last; + foreach (const QModelIndex &index, indices) + { + if (index.row() > last.row() || !last.isValid()) + { + last = index; + } + } + + return last; } int CategorizedView::categoryTop(const CategorizedView::Category *category) const @@ -231,14 +298,10 @@ int CategorizedView::contentWidth() const return width() - m_leftMargin - m_rightMargin; } -bool CategorizedView::lessThanCategoryPointer(const CategorizedView::Category *c1, const CategorizedView::Category *c2) -{ - return c1->text < c2->text; -} QList CategorizedView::sortedCategories() const { QList out = m_categories; - qSort(out.begin(), out.end(), &CategorizedView::lessThanCategoryPointer); + qSort(out.begin(), out.end(), [](const Category *c1, const Category *c2) { return c1->text < c2->text; }); return out; } @@ -266,85 +329,186 @@ void CategorizedView::mousePressEvent(QMouseEvent *event) { //endCategoryEditor(); - if (event->buttons() & Qt::LeftButton) + QPoint pos = event->pos(); + QPersistentModelIndex index = indexAt(pos); + + m_pressedIndex = index; + m_pressedAlreadySelected = selectionModel()->isSelected(m_pressedIndex); + QItemSelectionModel::SelectionFlags command = selectionCommand(index, event); + QPoint offset = QPoint(horizontalOffset(), verticalOffset()); + if (!(command & QItemSelectionModel::Current)) { - foreach (Category *category, m_categories) - { - if (category->iconRect.contains(event->pos())) - { - category->collapsed = !category->collapsed; - updateGeometries(); - viewport()->update(); - event->accept(); - return; - } - } + m_pressedPosition = pos + offset; + } + else if (!indexAt(m_pressedPosition - offset).isValid()) + { + m_pressedPosition = visualRect(currentIndex()).center() + offset; + } - for (int i = 0; i < model()->rowCount(); ++i) + m_pressedCategory = categoryAt(m_pressedPosition); + if (m_pressedCategory) + { + setState(m_pressedCategory->collapsed ? ExpandingState : CollapsingState); + event->accept(); + return; + } + + if (index.isValid() && (index.flags() & Qt::ItemIsEnabled)) + { + // we disable scrollTo for mouse press so the item doesn't change position + // when the user is interacting with it (ie. clicking on it) + bool autoScroll = hasAutoScroll(); + setAutoScroll(false); + selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate); + setAutoScroll(autoScroll); + QRect rect(m_pressedPosition - offset, pos); + if (command.testFlag(QItemSelectionModel::Toggle)) { - QModelIndex index = model()->index(i, 0); - if (visualRect(index).contains(event->pos())) - { - selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); - event->accept(); - return; - } + command &= ~QItemSelectionModel::Toggle; + m_ctrlDragSelectionFlag = selectionModel()->isSelected(index) ? QItemSelectionModel::Deselect : QItemSelectionModel::Select; + command |= m_ctrlDragSelectionFlag; } - } + setSelection(rect, command); + + // signal handlers may change the model + emit pressed(index); - QListView::mousePressEvent(event); + } else { + // Forces a finalize() even if mouse is pressed, but not on a item + selectionModel()->select(QModelIndex(), QItemSelectionModel::Select); + } } void CategorizedView::mouseMoveEvent(QMouseEvent *event) { - if (event->buttons() & Qt::LeftButton) + QPoint topLeft; + QPoint bottomRight = event->pos(); + + if (state() == ExpandingState || state() == CollapsingState) { - for (int i = 0; i < model()->rowCount(); ++i) + return; + } + + if (state() == DraggingState) + { + topLeft = m_pressedPosition - QPoint(horizontalOffset(), verticalOffset()); + if ((topLeft - event->pos()).manhattanLength() > QApplication::startDragDistance()) { - QModelIndex index = model()->index(i, 0); - if (visualRect(index).contains(event->pos())) - { - selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); - event->accept(); - return; - } + m_pressedIndex = QModelIndex(); + startDrag(model()->supportedDragActions()); + setState(NoState); + stopAutoScroll(); } + return; } - QListView::mouseMoveEvent(event); -} -void CategorizedView::mouseReleaseEvent(QMouseEvent *event) -{ - if (event->buttons() & Qt::LeftButton) + QPersistentModelIndex index = indexAt(bottomRight); + + if (selectionMode() != SingleSelection) { - for (int i = 0; i < model()->rowCount(); ++i) + topLeft = m_pressedPosition - QPoint(horizontalOffset(), verticalOffset()); + } + else + { + topLeft = bottomRight; + } + + if (m_pressedIndex.isValid() + && (state() != DragSelectingState) + && (event->buttons() != Qt::NoButton) + && !selectedIndexes().isEmpty()) + { + setState(DraggingState); + return; + } + + if ((event->buttons() & Qt::LeftButton) && selectionModel()) + { + setState(DragSelectingState); + QItemSelectionModel::SelectionFlags command = selectionCommand(index, event); + if (m_ctrlDragSelectionFlag != QItemSelectionModel::NoUpdate && command.testFlag(QItemSelectionModel::Toggle)) { - QModelIndex index = model()->index(i, 0); - if (visualRect(index).contains(event->pos())) - { - selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); - event->accept(); - return; - } + command &= ~QItemSelectionModel::Toggle; + command |= m_ctrlDragSelectionFlag; } - } - QListView::mouseReleaseEvent(event); + // Do the normalize ourselves, since QRect::normalized() is flawed + QRect selectionRect = QRect(topLeft, bottomRight); + setSelection(selectionRect, command); + + // set at the end because it might scroll the view + if (index.isValid() + && (index != selectionModel()->currentIndex()) + && (index.flags() & Qt::ItemIsEnabled)) + { + selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate); + } + } } -void CategorizedView::mouseDoubleClickEvent(QMouseEvent *event) +void CategorizedView::mouseReleaseEvent(QMouseEvent *event) { - /*endCategoryEditor(); + QPoint pos = event->pos(); + QPersistentModelIndex index = indexAt(pos); - foreach (Category *category, m_categories) + bool click = (index == m_pressedIndex && index.isValid()) || (m_pressedCategory && m_pressedCategory == categoryAt(pos)); + + if (click && m_pressedCategory) { - if (category->textRect.contains(event->pos()) && m_categoryEditor == 0) + if (state() == ExpandingState) { - startCategoryEditor(category); + m_pressedCategory->collapsed = false; + updateGeometries(); + viewport()->update(); event->accept(); return; } - }*/ + else if (state() == CollapsingState) + { + m_pressedCategory->collapsed = true; + updateGeometries(); + viewport()->update(); + event->accept(); + return; + } + } + + m_ctrlDragSelectionFlag = QItemSelectionModel::NoUpdate; + + setState(NoState); - QListView::mouseDoubleClickEvent(event); + if (click) + { + if (event->button() == Qt::LeftButton) + { + emit clicked(index); + } + QStyleOptionViewItem option = viewOptions(); + if (m_pressedAlreadySelected) + { + option.state |= QStyle::State_Selected; + } + if ((model()->flags(index) & Qt::ItemIsEnabled) + && style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, &option, this)) + { + emit activated(index); + } + } +} +void CategorizedView::mouseDoubleClickEvent(QMouseEvent *event) +{ + QModelIndex index = indexAt(event->pos()); + if (!index.isValid() + || !(index.flags() & Qt::ItemIsEnabled) + || (m_pressedIndex != index)) + { + QMouseEvent me(QEvent::MouseButtonPress, + event->localPos(), event->windowPos(), event->screenPos(), + event->button(), event->buttons(), event->modifiers()); + mousePressEvent(&me); + return; + } + // signal handlers may change the model + QPersistentModelIndex persistent = index; + emit doubleClicked(persistent); } void CategorizedView::paintEvent(QPaintEvent *event) { @@ -385,6 +549,33 @@ void CategorizedView::paintEvent(QPaintEvent *event) } itemDelegate()->paint(&painter, option, index); } + + if (!m_lastDragPosition.isNull()) + { + QPair pair = rowDropPos(m_lastDragPosition); + Category *category = pair.first; + int row = pair.second; + if (category) + { + int internalRow = row - firstItemForCategory(category).row(); + qDebug() << internalRow << numItemsForCategory(category) << model()->index(row, 0).data().toString(); + QLine line; + if (internalRow >= numItemsForCategory(category)) + { + QRect toTheRightOfRect = visualRect(lastItemForCategory(category)); + line = QLine(toTheRightOfRect.topRight(), toTheRightOfRect.bottomRight()); + } + else + { + QRect toTheLeftOfRect = visualRect(model()->index(row, 0)); + line = QLine(toTheLeftOfRect.topLeft(), toTheLeftOfRect.bottomLeft()); + } + painter.save(); + painter.setPen(QPen(Qt::black, 3)); + painter.drawLine(line); + painter.restore(); + } + } } void CategorizedView::resizeEvent(QResizeEvent *event) { @@ -400,18 +591,33 @@ void CategorizedView::resizeEvent(QResizeEvent *event) void CategorizedView::dragEnterEvent(QDragEnterEvent *event) { - // TODO + if (!isDragEventAccepted(event)) + { + return; + } + m_lastDragPosition = event->pos(); + viewport()->update(); + event->accept(); } void CategorizedView::dragMoveEvent(QDragMoveEvent *event) { - // TODO + if (!isDragEventAccepted(event)) + { + return; + } + m_lastDragPosition = event->pos(); + viewport()->update(); + event->accept(); } void CategorizedView::dragLeaveEvent(QDragLeaveEvent *event) { - // TODO + m_lastDragPosition = QPoint(); + viewport()->update(); } void CategorizedView::dropEvent(QDropEvent *event) { + m_lastDragPosition = QPoint(); + stopAutoScroll(); setState(NoState); @@ -420,93 +626,68 @@ void CategorizedView::dropEvent(QDropEvent *event) return; } - // check that we aren't on a category header and calculate which category we're in - Category *category = 0; + QPair dropPos = rowDropPos(event->pos()); + const Category *category = dropPos.first; + const int row = dropPos.second; + + if (row == -1) { - int y = 0; - foreach (Category *cat, m_categories) - { - if (event->pos().y() > y && event->pos().y() < (y + cat->headerHeight())) - { - viewport()->update(); - return; - } - y += cat->totalHeight() + m_categoryMargin; - if (event->pos().y() < y) - { - category = cat; - break; - } - } + viewport()->update(); + return; } - // calculate the internal column - int internalColumn = -1; + const QString categoryText = category->text; + if (model()->dropMimeData(event->mimeData(), Qt::MoveAction, row, 0, QModelIndex())) { - const int itemWidth = itemSize().width(); - for (int i = 0, c = 0; - i < contentWidth(); - i += itemWidth, ++c) - { - if (event->pos().x() > (i - itemWidth / 2) && - event->pos().x() < (i + itemWidth / 2)) - { - internalColumn = c; - break; - } - } - if (internalColumn == -1) - { - viewport()->update(); - return; - } + model()->setData(model()->index(row, 0), categoryText, CategoryRole); + event->setDropAction(Qt::MoveAction); + event->accept(); } + updateGeometries(); + viewport()->update(); +} - // calculate the internal row - int internalRow = -1; +void CategorizedView::startDrag(Qt::DropActions supportedActions) +{ + QModelIndexList indexes = selectionModel()->selectedIndexes(); + if (indexes.count() > 0) { - const int itemHeight = itemSize().height(); - const int top = categoryTop(category); - for (int i = top + category->headerHeight(), r = 0; - i < top + category->totalHeight(); - i += itemHeight, ++r) + QMimeData *data = model()->mimeData(indexes); + if (!data) { - if (event->pos().y() > i && event->pos().y() < (i + itemHeight)) - { - internalRow = r; - break; - } + return; } - if (internalRow == -1) + QRect rect; + QPixmap pixmap = renderToPixmap(indexes, &rect); + rect.adjust(horizontalOffset(), verticalOffset(), 0, 0); + QDrag *drag = new QDrag(this); + drag->setPixmap(pixmap); + drag->setMimeData(data); + drag->setHotSpot(m_pressedPosition - rect.topLeft()); + Qt::DropAction defaultDropAction = Qt::IgnoreAction; + if (this->defaultDropAction() != Qt::IgnoreAction && (supportedActions & this->defaultDropAction())) { - viewport()->update(); - return; + defaultDropAction = this->defaultDropAction(); } - } - - QList indices = itemsForCategory(category); - - // flaten the internalColumn/internalRow to one row - int categoryRow; - { - for (int i = 0; i < internalRow; ++i) + if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction) { - if (i == internalRow) - { - break; + const QItemSelection selection = selectionModel()->selection(); + + for (auto it = selection.constBegin(); it != selection.constEnd(); ++it) { + QModelIndex parent = (*it).parent(); + if ((*it).left() != 0) + { + continue; + } + if ((*it).right() != (model()->columnCount(parent) - 1)) + { + continue; + } + int count = (*it).bottom() - (*it).top() + 1; + model()->removeRows((*it).top(), count, parent); } - categoryRow += itemsPerRow(); } - categoryRow += internalColumn; - } - - int row = indices.at(categoryRow).row(); - if (model()->dropMimeData(event->mimeData(), Qt::MoveAction, row, 0, QModelIndex())) - { - event->setDropAction(Qt::MoveAction); - event->accept(); } - updateGeometries(); } bool lessThanQModelIndex(const QModelIndex &i1, const QModelIndex &i2) @@ -520,34 +701,39 @@ QRect CategorizedView::visualRect(const QModelIndex &index) const return QRect(); } - const Category *cat = category(index); - QList indices = itemsForCategory(cat); - qSort(indices.begin(), indices.end(), &lessThanQModelIndex); - int x = 0; - int y = 0; - const int perRow = itemsPerRow(); - for (int i = 0; i < indices.size(); ++i) + if (!m_cachedVisualRects.contains(index)) { - if (indices.at(i) == index) - { - break; - } - ++x; - if (x == perRow) + const Category *cat = category(index); + QList indices = itemsForCategory(cat); + qSort(indices.begin(), indices.end(), &lessThanQModelIndex); + int x = 0; + int y = 0; + const int perRow = itemsPerRow(); + for (int i = 0; i < indices.size(); ++i) { - x = 0; - ++y; + if (indices.at(i) == index) + { + break; + } + ++x; + if (x == perRow) + { + x = 0; + ++y; + } } - } - QSize size = itemSize(); + QSize size = itemSize(); - QRect out; - out.setTop(categoryTop(cat) + cat->headerHeight() + 5 + y * size.height()); - out.setLeft(x * size.width()); - out.setSize(size); + QRect *out = new QRect; + out->setTop(categoryTop(cat) + cat->headerHeight() + 5 + y * size.height()); + out->setLeft(x * size.width()); + out->setSize(size); - return out; + m_cachedVisualRects.insert(index, out); + } + + return *m_cachedVisualRects.object(index); } /* void CategorizedView::startCategoryEditor(Category *category) @@ -585,3 +771,176 @@ void CategorizedView::endCategoryEditor() updateGeometries(); } */ + +QModelIndex CategorizedView::indexAt(const QPoint &point) const +{ + for (int i = 0; i < model()->rowCount(); ++i) + { + QModelIndex index = model()->index(i, 0); + if (visualRect(index).contains(point)) + { + return index; + } + } + return QModelIndex(); +} +void CategorizedView::setSelection(const QRect &rect, const QItemSelectionModel::SelectionFlags commands) +{ + QItemSelection selection; + for (int i = 0; i < model()->rowCount(); ++i) + { + QModelIndex index = model()->index(i, 0); + if (visualRect(index).intersects(rect)) + { + selection.merge(QItemSelection(index, index), QItemSelectionModel::Select); + } + } + selectionModel()->select(selection, commands); +} + +QPixmap CategorizedView::renderToPixmap(const QModelIndexList &indices, QRect *r) const +{ + Q_ASSERT(r); + QList > paintPairs = draggablePaintPairs(indices, r); + if (paintPairs.isEmpty()) + { + return QPixmap(); + } + QPixmap pixmap(r->size()); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + QStyleOptionViewItem option = viewOptions(); + option.state |= QStyle::State_Selected; + for (int j = 0; j < paintPairs.count(); ++j) + { + option.rect = paintPairs.at(j).first.translated(-r->topLeft()); + const QModelIndex ¤t = paintPairs.at(j).second; + itemDelegate()->paint(&painter, option, current); + } + return pixmap; +} +QList > CategorizedView::draggablePaintPairs(const QModelIndexList &indices, QRect *r) const +{ + Q_ASSERT(r); + QRect &rect = *r; + const QRect viewportRect = viewport()->rect(); + QList > ret; + for (int i = 0; i < indices.count(); ++i) { + const QModelIndex &index = indices.at(i); + const QRect current = visualRect(index); + if (current.intersects(viewportRect)) { + ret += qMakePair(current, index); + rect |= current; + } + } + rect &= viewportRect; + return ret; +} + +bool CategorizedView::isDragEventAccepted(QDropEvent *event) +{ + if (event->source() != this) + { + return false; + } + if (!listsIntersect(event->mimeData()->formats(), model()->mimeTypes())) + { + return false; + } + if (!model()->canDropMimeData(event->mimeData(), event->dropAction(), rowDropPos(event->pos()).second, 0, QModelIndex())) + { + return false; + } + return true; +} +QPair CategorizedView::rowDropPos(const QPoint &pos) +{ + // check that we aren't on a category header and calculate which category we're in + Category *category = 0; + { + int y = 0; + foreach (Category *cat, m_categories) + { + if (pos.y() > y && pos.y() < (y + cat->headerHeight())) + { + return qMakePair(nullptr, -1); + } + y += cat->totalHeight() + m_categoryMargin; + if (pos.y() < y) + { + category = cat; + break; + } + } + if (category == 0) + { + return qMakePair(nullptr, -1); + } + } + + // calculate the internal column + int internalColumn = -1; + { + const int itemWidth = itemSize().width(); + for (int i = 0, c = 0; + i < contentWidth(); + i += itemWidth, ++c) + { + if (pos.x() > (i - itemWidth / 2) && + pos.x() < (i + itemWidth / 2)) + { + internalColumn = c; + break; + } + } + if (internalColumn == -1) + { + return qMakePair(nullptr, -1); + } + } + + // calculate the internal row + int internalRow = -1; + { + const int itemHeight = itemSize().height(); + const int top = categoryTop(category); + for (int i = top + category->headerHeight(), r = 0; + i < top + category->totalHeight(); + i += itemHeight, ++r) + { + if (pos.y() > i && pos.y() < (i + itemHeight)) + { + internalRow = r; + break; + } + } + if (internalRow == -1) + { + return qMakePair(nullptr, -1); + } + } + + QList indices = itemsForCategory(category); + + // flaten the internalColumn/internalRow to one row + int categoryRow = 0; + { + for (int i = 0; i < internalRow; ++i) + { + if ((i + 1) >= internalRow) + { + break; + } + categoryRow += itemsPerRow(); + } + categoryRow += internalColumn; + } + + // this is used if we're past the last item + if (internalColumn >= qMin(itemsPerRow(), indices.size())) + { + return qMakePair(category, indices.last().row() + 1); + } + + return qMakePair(category, indices.at(categoryRow).row()); +} diff --git a/CategorizedView.h b/CategorizedView.h index 1e918496..0756629a 100644 --- a/CategorizedView.h +++ b/CategorizedView.h @@ -3,6 +3,7 @@ #include #include +#include class CategorizedView : public QListView { @@ -18,6 +19,8 @@ public: }; virtual QRect visualRect(const QModelIndex &index) const; + QModelIndex indexAt(const QPoint &point) const; + void setSelection(const QRect &rect, const QItemSelectionModel::SelectionFlags commands) override; protected slots: void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles); @@ -39,6 +42,8 @@ protected: void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *event) override; + void startDrag(Qt::DropActions supportedActions) override; + private: struct Category { @@ -59,6 +64,8 @@ private: friend struct Category; QList m_categories; + mutable QCache > m_cachedCategoryToIndexMapping; + mutable QCache m_cachedVisualRects; int m_leftMargin; int m_rightMargin; @@ -69,8 +76,11 @@ private: Category *category(const QModelIndex &index) const; Category *category(const QString &cat) const; + Category *categoryAt(const QPoint &pos) const; int numItemsForCategory(const Category *category) const; QList itemsForCategory(const Category *category) const; + QModelIndex firstItemForCategory(const Category *category) const; + QModelIndex lastItemForCategory(const Category *category) const; int categoryTop(const Category *category) const; @@ -91,6 +101,21 @@ private: private slots: void endCategoryEditor();*/ + +private: + QPoint m_pressedPosition; + QPersistentModelIndex m_pressedIndex; + bool m_pressedAlreadySelected; + Category *m_pressedCategory; + QItemSelectionModel::SelectionFlag m_ctrlDragSelectionFlag; + QPoint m_lastDragPosition; + + QPixmap renderToPixmap(const QModelIndexList &indices, QRect *r) const; + QList > draggablePaintPairs(const QModelIndexList &indices, QRect *r) const; + + bool isDragEventAccepted(QDropEvent *event); + + QPair rowDropPos(const QPoint &pos); }; #endif // WIDGET_H -- cgit From c71808446b3e95e4fefb91b69c2cc51e4c4918cc Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Thu, 26 Dec 2013 21:23:21 +0100 Subject: Fix a bug --- CategorizedView.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 95505fd7..4d9a4a62 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -690,10 +690,6 @@ void CategorizedView::startDrag(Qt::DropActions supportedActions) } } -bool lessThanQModelIndex(const QModelIndex &i1, const QModelIndex &i2) -{ - return i1.data() < i2.data(); -} QRect CategorizedView::visualRect(const QModelIndex &index) const { if (!index.isValid() || isIndexHidden(index) || index.column() > 0) @@ -705,7 +701,6 @@ QRect CategorizedView::visualRect(const QModelIndex &index) const { const Category *cat = category(index); QList indices = itemsForCategory(cat); - qSort(indices.begin(), indices.end(), &lessThanQModelIndex); int x = 0; int y = 0; const int perRow = itemsPerRow(); -- cgit From acbbdf319a7378a4029965a52222e7a84c33253f Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Thu, 26 Dec 2013 21:24:42 +0100 Subject: Remove a debug message --- CategorizedView.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 4d9a4a62..780674eb 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -558,7 +558,6 @@ void CategorizedView::paintEvent(QPaintEvent *event) if (category) { int internalRow = row - firstItemForCategory(category).row(); - qDebug() << internalRow << numItemsForCategory(category) << model()->index(row, 0).data().toString(); QLine line; if (internalRow >= numItemsForCategory(category)) { -- cgit From 53db8edb851917809209e4473eef2a66651d6047 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Thu, 26 Dec 2013 22:02:25 +0100 Subject: Fixing several d&d bugs --- CategorizedView.cpp | 26 +++++++++++--------------- main.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 780674eb..1860f095 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -872,6 +872,8 @@ QPair CategorizedView::rowDropPos(const QPoint } } + QList indices = itemsForCategory(category); + // calculate the internal column int internalColumn = -1; { @@ -912,26 +914,20 @@ QPair CategorizedView::rowDropPos(const QPoint { return qMakePair(nullptr, -1); } - } - - QList indices = itemsForCategory(category); - - // flaten the internalColumn/internalRow to one row - int categoryRow = 0; - { - for (int i = 0; i < internalRow; ++i) + // this happens if we're in the margin between a one category and another + // categories header + if (internalRow > (indices.size() / itemsPerRow())) { - if ((i + 1) >= internalRow) - { - break; - } - categoryRow += itemsPerRow(); + return qMakePair(nullptr, -1); } - categoryRow += internalColumn; } + // flaten the internalColumn/internalRow to one row + int categoryRow = internalRow * itemsPerRow() + internalColumn; + // this is used if we're past the last item - if (internalColumn >= qMin(itemsPerRow(), indices.size())) + int numItemsInLastRow = indices.size() % itemsPerRow(); + if (internalColumn >= numItemsInLastRow) { return qMakePair(category, indices.last().row() + 1); } diff --git a/main.cpp b/main.cpp index 24d7075e..427ae17a 100644 --- a/main.cpp +++ b/main.cpp @@ -1,6 +1,7 @@ #include "CategorizedView.h" #include #include +#include #include "CategorizedProxyModel.h" @@ -10,6 +11,18 @@ QPixmap icon(const Qt::GlobalColor color) p.fill(QColor(color)); return p; } +QPixmap icon(const int number) +{ + QPixmap p = icon(Qt::white); + QPainter painter(&p); + QFont font = painter.font(); + font.setBold(true); + font.setPixelSize(28); + painter.setFont(font); + painter.drawText(QRect(QPoint(0, 0), p.size()), Qt::AlignVCenter | Qt::AlignHCenter, QString::number(number)); + painter.end(); + return p; +} QStandardItem *createItem(const Qt::GlobalColor color, const QString &text, const QString &category) { QStandardItem *item = new QStandardItem; @@ -19,6 +32,15 @@ QStandardItem *createItem(const Qt::GlobalColor color, const QString &text, cons item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); return item; } +QStandardItem *createItem(const int index, const QString &category) +{ + QStandardItem *item = new QStandardItem; + item->setText(QString("Item #%1").arg(index)); + item->setData(icon(index), Qt::DecorationRole); + item->setData(category, CategorizedView::CategoryRole); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); + return item; +} int main(int argc, char *argv[]) { @@ -41,6 +63,11 @@ int main(int argc, char *argv[]) model.setItem(8, createItem(Qt::darkGreen, "Dark Green", "")); model.setItem(9, createItem(Qt::green, "Green", "")); + for (int i = 0; i < 21; ++i) + { + model.setItem(i + 10, createItem(i+1, "Items 1-20")); + } + CategorizedProxyModel pModel; pModel.setSourceModel(&model); -- cgit From f8d835cd22de89bc130ff0413228cfea0ebfd8ac Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Thu, 26 Dec 2013 22:40:26 +0100 Subject: Fix scrolling --- CategorizedView.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 1860f095..6164cde6 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -9,6 +9,7 @@ #include #include #include +#include template bool listsIntersect(const QList &l1, const QList t2) @@ -182,6 +183,22 @@ void CategorizedView::updateGeometries() qDeleteAll(m_categories); m_categories = cats.values(); + if (m_categories.isEmpty()) + { + verticalScrollBar()->setRange(0, 0); + } + else + { + int totalHeight = 0; + foreach (const Category *category, m_categories) + { + totalHeight += category->totalHeight() + m_categoryMargin; + } + // remove the last margin (we don't want it) + totalHeight -= m_categoryMargin; + verticalScrollBar()->setRange(0, totalHeight- height()); + } + update(); } @@ -513,6 +530,8 @@ void CategorizedView::mouseDoubleClickEvent(QMouseEvent *event) void CategorizedView::paintEvent(QPaintEvent *event) { QPainter painter(this->viewport()); + QPoint offset(horizontalOffset(), verticalOffset()); + painter.translate(-offset); int y = 0; for (int i = 0; i < m_categories.size(); ++i) -- cgit From 01092206783f74ce14f31d328cdac025fd90fe16 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Fri, 27 Dec 2013 00:03:24 +0100 Subject: Take the spacing into account --- CategorizedView.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index 6164cde6..c134220f 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -97,6 +97,7 @@ CategorizedView::CategorizedView(QWidget *parent) setWordWrap(true); setDragDropMode(QListView::InternalMove); setAcceptDrops(true); + setSpacing(10); m_cachedCategoryToIndexMapping.setMaxCost(50); m_cachedVisualRects.setMaxCost(50); @@ -308,7 +309,7 @@ int CategorizedView::categoryTop(const CategorizedView::Category *category) cons int CategorizedView::itemsPerRow() const { - return qFloor((qreal)contentWidth() / (qreal)itemSize().width()); + return qFloor((qreal)(contentWidth()) / (qreal)(itemWidth() + spacing())); } int CategorizedView::contentWidth() const { @@ -740,7 +741,7 @@ QRect CategorizedView::visualRect(const QModelIndex &index) const QRect *out = new QRect; out->setTop(categoryTop(cat) + cat->headerHeight() + 5 + y * size.height()); - out->setLeft(x * size.width()); + out->setLeft(spacing() + x * itemWidth() + x * spacing()); out->setSize(size); m_cachedVisualRects.insert(index, out); -- cgit From 4662fbd29891ccb9120df82d17a34a7619242827 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Mon, 30 Dec 2013 18:45:40 +0100 Subject: Make the MultiMC delegate fully usable. Dynamic row heights. --- CMakeLists.txt | 2 + CategorizedView.cpp | 104 ++++++++++++++------- CategorizedView.h | 9 +- InstanceDelegate.cpp | 254 +++++++++++++++++++++++++++++++++++++++++++++++++++ InstanceDelegate.h | 27 ++++++ main.cpp | 4 +- 6 files changed, 363 insertions(+), 37 deletions(-) create mode 100644 InstanceDelegate.cpp create mode 100644 InstanceDelegate.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a246bcf..b94cf53e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,8 @@ set(SOURCES CategorizedView.cpp CategorizedProxyModel.h CategorizedProxyModel.cpp + InstanceDelegate.h + InstanceDelegate.cpp ) add_executable(GroupView ${SOURCES}) diff --git a/CategorizedView.cpp b/CategorizedView.cpp index c134220f..bdb0b222 100644 --- a/CategorizedView.cpp +++ b/CategorizedView.cpp @@ -80,7 +80,22 @@ int CategorizedView::Category::contentHeight() const return 0; } const int rows = qMax(1, qCeil((qreal)view->numItemsForCategory(this) / (qreal)view->itemsPerRow())); - return view->itemSize().height() * rows; + QMap rowToHeightMapping; + foreach (const QModelIndex &index, view->itemsForCategory(this)) + { + int row = view->categoryInternalPosition(index).second; + if (!rowToHeightMapping.contains(row)) + { + rowToHeightMapping.insert(row, view->itemSize(index).height()); + } + } + int result = 0; + for (int i = 0; i < rows; ++i) + { + Q_ASSERT(rowToHeightMapping.contains(i)); + result += rowToHeightMapping[i]; + } + return result; } QSize CategorizedView::Category::categoryTotalSize() const { @@ -153,9 +168,10 @@ void CategorizedView::updateGeometries() { QListView::updateGeometries(); - m_cachedItemSize = QSize(); + m_cachedItemWidth = -1; m_cachedCategoryToIndexMapping.clear(); m_cachedVisualRects.clear(); + m_cachedItemSizes.clear(); QMap cats; @@ -323,24 +339,59 @@ QList CategorizedView::sortedCategories() const return out; } -QSize CategorizedView::itemSize(const QStyleOptionViewItem &option) const +int CategorizedView::itemWidth() const { - if (!m_cachedItemSize.isValid()) + if (m_cachedItemWidth == -1) { - QModelIndex sample = model()->index(model()->rowCount() -1, 0); - const QAbstractItemDelegate *delegate = itemDelegate(); - if (delegate) + m_cachedItemWidth = itemDelegate()->sizeHint(viewOptions(), model()->index(model()->rowCount() -1, 0)).width(); + } + return m_cachedItemWidth; +} + +QSize CategorizedView::itemSize(const QModelIndex &index) const +{ + if (!m_cachedItemSizes.contains(index)) + { + QModelIndexList indices; + int internalRow = categoryInternalPosition(index).second; + foreach (const QModelIndex &i, itemsForCategory(category(index))) + { + if (categoryInternalPosition(i).second == internalRow) + { + indices.append(i); + } + } + + int largestHeight = 0; + foreach (const QModelIndex &i, indices) { - m_cachedItemSize = delegate->sizeHint(option, sample); - m_cachedItemSize.setWidth(m_cachedItemSize.width() + 20); - m_cachedItemSize.setHeight(m_cachedItemSize.height() + 20); + largestHeight = qMax(largestHeight, itemDelegate()->sizeHint(viewOptions(), i).height()); } - else + m_cachedItemSizes.insert(index, new QSize(itemWidth(), largestHeight)); + } + return *m_cachedItemSizes.object(index); +} + +QPair CategorizedView::categoryInternalPosition(const QModelIndex &index) const +{ + QList indices = itemsForCategory(category(index)); + int x = 0; + int y = 0; + const int perRow = itemsPerRow(); + for (int i = 0; i < indices.size(); ++i) + { + if (indices.at(i) == index) + { + break; + } + ++x; + if (x == perRow) { - m_cachedItemSize = QSize(); + x = 0; + ++y; } } - return m_cachedItemSize; + return qMakePair(x, y); } void CategorizedView::mousePressEvent(QMouseEvent *event) @@ -719,25 +770,11 @@ QRect CategorizedView::visualRect(const QModelIndex &index) const if (!m_cachedVisualRects.contains(index)) { const Category *cat = category(index); - QList indices = itemsForCategory(cat); - int x = 0; - int y = 0; - const int perRow = itemsPerRow(); - for (int i = 0; i < indices.size(); ++i) - { - if (indices.at(i) == index) - { - break; - } - ++x; - if (x == perRow) - { - x = 0; - ++y; - } - } + QPair pos = categoryInternalPosition(index); + int x = pos.first; + int y = pos.second; - QSize size = itemSize(); + QSize size = itemSize(index); QRect *out = new QRect; out->setTop(categoryTop(cat) + cat->headerHeight() + 5 + y * size.height()); @@ -897,7 +934,7 @@ QPair CategorizedView::rowDropPos(const QPoint // calculate the internal column int internalColumn = -1; { - const int itemWidth = itemSize().width(); + const int itemWidth = this->itemWidth(); for (int i = 0, c = 0; i < contentWidth(); i += itemWidth, ++c) @@ -918,7 +955,8 @@ QPair CategorizedView::rowDropPos(const QPoint // calculate the internal row int internalRow = -1; { - const int itemHeight = itemSize().height(); + // FIXME rework the drag and drop code + const int itemHeight = 0; //itemSize().height(); const int top = categoryTop(category); for (int i = top + category->headerHeight(), r = 0; i < top + category->totalHeight(); diff --git a/CategorizedView.h b/CategorizedView.h index 0756629a..e98e7c5e 100644 --- a/CategorizedView.h +++ b/CategorizedView.h @@ -91,9 +91,10 @@ private: QList sortedCategories() const; private: - mutable QSize m_cachedItemSize; - QSize itemSize(const QStyleOptionViewItem &option) const; - QSize itemSize() const { return itemSize(viewOptions()); } + mutable int m_cachedItemWidth; + mutable QCache m_cachedItemSizes; + int itemWidth() const; + QSize itemSize(const QModelIndex &index) const; /*QLineEdit *m_categoryEditor; Category *m_editedCategory; @@ -110,6 +111,8 @@ private: QItemSelectionModel::SelectionFlag m_ctrlDragSelectionFlag; QPoint m_lastDragPosition; + QPair categoryInternalPosition(const QModelIndex &index) const; + QPixmap renderToPixmap(const QModelIndexList &indices, QRect *r) const; QList > draggablePaintPairs(const QModelIndexList &indices, QRect *r) const; diff --git a/InstanceDelegate.cpp b/InstanceDelegate.cpp new file mode 100644 index 00000000..5020b8b6 --- /dev/null +++ b/InstanceDelegate.cpp @@ -0,0 +1,254 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "InstanceDelegate.h" +#include +#include +#include +#include +#include + +// Origin: Qt +static void viewItemTextLayout(QTextLayout &textLayout, int lineWidth, qreal &height, + qreal &widthUsed) +{ + height = 0; + widthUsed = 0; + textLayout.beginLayout(); + QString str = textLayout.text(); + while (true) + { + QTextLine line = textLayout.createLine(); + if (!line.isValid()) + break; + if (line.textLength() == 0) + break; + line.setLineWidth(lineWidth); + line.setPosition(QPointF(0, height)); + height += line.height(); + widthUsed = qMax(widthUsed, line.naturalTextWidth()); + } + textLayout.endLayout(); +} + +#define QFIXED_MAX (INT_MAX / 256) + +ListViewDelegate::ListViewDelegate(QObject *parent) : QStyledItemDelegate(parent) +{ +} + +void drawSelectionRect(QPainter *painter, const QStyleOptionViewItemV4 &option, + const QRect &rect) +