1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "RDHeaderView.h"
#include <QDebug>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QPointer>
#include "Code/QRDUtils.h"
/////////////////////////////////////////////////////////////////////////////////
//
// this file contains a few hardcoded assumptions for my use case, especially
// with the 'custom sizing' mode that allows merging sections and pinning sections
// and so on.
//
// * No handling for moving/rearranging/hiding sections with the custom sizing
// mode. Just needs more careful handling and distinguishing between logical
// and visual indices.
// * Probably a few places vertical orientation isn't handled right, but that
// shouldn't be too bad.
//
/////////////////////////////////////////////////////////////////////////////////
RDHeaderView::RDHeaderView(Qt::Orientation orient, QWidget *parent) : QHeaderView(orient, parent)
{
m_sectionPreview = new QLabel(this);
setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
}
RDHeaderView::~RDHeaderView()
{
}
QSize RDHeaderView::sizeHint() const
{
if(!m_customSizing)
return QHeaderView::sizeHint();
return m_sizeHint;
}
void RDHeaderView::setModel(QAbstractItemModel *model)
{
QAbstractItemModel *m = this->model();
if(m)
{
QObject::disconnect(m, &QAbstractItemModel::headerDataChanged, this,
&RDHeaderView::headerDataChanged);
QObject::disconnect(m, &QAbstractItemModel::columnsInserted, this,
&RDHeaderView::columnsInserted);
QObject::disconnect(m, &QAbstractItemModel::rowsInserted, this, &RDHeaderView::rowsChanged);
QObject::disconnect(m, &QAbstractItemModel::rowsRemoved, this, &RDHeaderView::rowsChanged);
}
QHeaderView::setModel(model);
QObject::connect(model, &QAbstractItemModel::headerDataChanged, this,
&RDHeaderView::headerDataChanged);
QObject::connect(model, &QAbstractItemModel::columnsInserted, this, &RDHeaderView::columnsInserted);
QObject::connect(model, &QAbstractItemModel::rowsInserted, this, &RDHeaderView::rowsChanged);
QObject::connect(model, &QAbstractItemModel::rowsRemoved, this, &RDHeaderView::rowsChanged);
}
void RDHeaderView::reset()
{
if(m_customSizing)
cacheSections();
}
void RDHeaderView::cacheSections()
{
if(m_suppressSectionCache)
return;
QAbstractItemModel *m = this->model();
int oldCount = m_sections.count();
m_sections.resize(m->columnCount());
// give new sections a default minimum size
for(int col = oldCount; col < m_sections.count(); col++)
m_sections[col].size = 10;
for(int col = 0; col < m_sections.count(); col++)
{
if(m_columnGroupRole > 0)
{
QVariant v = m->data(m->index(0, col), m_columnGroupRole);
if(v.isValid())
m_sections[col].group = v.toInt();
else
m_sections[col].group = -m_columnGroupRole - col;
if(col > 0)
{
m_sections[col - 1].groupGap =
(m_sections[col].group != m_sections[col - 1].group) && m_sections[col].group >= 0;
}
}
else
{
m_sections[col].group = col;
m_sections[col].groupGap = true;
}
}
int accum = 0;
for(int col = 0; col < m_sections.count(); col++)
{
if(col == m_pinnedColumns)
m_pinnedWidth = accum;
m_sections[col].offset = accum;
accum += m_sections[col].size;
if(hasGroupGap(col))
accum += groupGapSize();
}
if(m_pinnedColumns >= m_sections.count())
m_pinnedWidth = m_pinnedColumns;
QHeaderView::initializeSections();
QStyleOptionHeader opt;
initStyleOption(&opt);
QFont f = font();
f.setBold(true);
opt.section = 0;
opt.fontMetrics = QFontMetrics(f);
opt.text = m->headerData(0, orientation(), Qt::DisplayRole).toString();
m_sizeHint = style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this);
m_sizeHint.setWidth(accum);
viewport()->update(viewport()->rect());
}
int RDHeaderView::sectionSize(int logicalIndex) const
{
if(m_customSizing)
{
if(logicalIndex < 0 || logicalIndex >= m_sections.count())
return 0;
return m_sections[logicalIndex].size;
}
return QHeaderView::sectionSize(logicalIndex);
}
int RDHeaderView::sectionViewportPosition(int logicalIndex) const
{
if(m_customSizing)
{
if(logicalIndex < 0 || logicalIndex >= m_sections.count())
return -1;
int offs = m_sections[logicalIndex].offset;
if(logicalIndex >= m_pinnedColumns)
offs -= offset();
return offs;
}
return QHeaderView::sectionViewportPosition(logicalIndex);
}
int RDHeaderView::visualIndexAt(int position) const
{
if(m_customSizing)
{
if(m_sections.isEmpty())
return -1;
if(position >= m_pinnedWidth)
position += offset();
SectionData search;
search.offset = position;
auto it = std::lower_bound(
m_sections.begin(), m_sections.end(), search,
[](const SectionData &a, const SectionData &b) { return a.offset <= b.offset; });
if(it != m_sections.begin())
--it;
if(it->offset <= position &&
position < (it->offset + it->size + (it->groupGap ? groupGapSize() : 0)))
return (it - m_sections.begin());
return -1;
}
return QHeaderView::visualIndexAt(position);
}
int RDHeaderView::logicalIndexAt(int position) const
{
return visualIndexAt(position);
}
int RDHeaderView::count() const
{
if(m_customSizing)
return m_sections.count();
return QHeaderView::count();
}
void RDHeaderView::resizeSection(int logicalIndex, int size)
{
if(!m_customSizing)
return QHeaderView::resizeSection(logicalIndex, size);
if(logicalIndex >= 0 && logicalIndex < m_sections.count())
{
int oldSize = m_sections[logicalIndex].size;
m_sections[logicalIndex].size = size;
emit sectionResized(logicalIndex, oldSize, size);
}
cacheSections();
}
void RDHeaderView::resizeSections(QHeaderView::ResizeMode mode)
{
if(!m_sectionStretchHints.isEmpty())
{
resizeSectionsWithHints();
return;
}
if(!m_customSizing)
return resizeSections(mode);
if(mode != ResizeToContents)
return;
QAbstractItemModel *m = this->model();
int rowCount = m->rowCount();
for(int col = 0; col < m_sections.count(); col++)
{
QSize sz;
for(int row = 0; row < rowCount; row++)
{
QVariant v = m->data(m->index(row, col), Qt::SizeHintRole);
if(v.isValid() && v.canConvert<QSize>())
sz = sz.expandedTo(v.value<QSize>());
}
int oldSize = m_sections[col].size;
m_sections[col].size = sz.width();
emit sectionResized(col, oldSize, sz.width());
}
}
void RDHeaderView::resizeSections(const QList<int> &sizes)
{
if(!m_customSizing)
{
for(int i = 0; i < qMin(sizes.count(), QHeaderView::count()); i++)
{
QHeaderView::resizeSection(i, sizes[i]);
}
return;
}
for(int i = 0; i < qMin(sizes.count(), m_sections.count()); i++)
{
int oldSize = m_sections[i].size;
m_sections[i].size = sizes[i];
emit sectionResized(i, oldSize, sizes[i]);
}
cacheSections();
}
bool RDHeaderView::hasGroupGap(int columnIndex) const
{
if(columnIndex >= 0 && columnIndex < m_sections.count())
return m_sections[columnIndex].groupGap;
return false;
}
bool RDHeaderView::hasGroupTitle(int columnIndex) const
{
if(columnIndex == m_sections.count() - 1)
return true;
if(columnIndex >= 0 && columnIndex < m_sections.count())
return m_sections[columnIndex].groupGap || m_sections[columnIndex].group < 0;
return false;
}
void RDHeaderView::cacheSectionMinSizes()
{
m_sectionMinSizes.resize(count());
for(int i = 0; i < m_sectionMinSizes.count(); i++)
{
int sz = 0;
// see if we can fetch the column/row size hint from the item view
QAbstractItemView *view = qobject_cast<QAbstractItemView *>(parent());
if(view)
{
if(orientation() == Qt::Horizontal)
sz = view->sizeHintForColumn(i);
else
sz = view->sizeHintForRow(i);
}
// also include the size for the header as another minimum
if(orientation() == Qt::Horizontal)
sz = qMax(sz, sectionSizeFromContents(i).width());
else
sz = qMax(sz, sectionSizeFromContents(i).height());
// finally respect the minimum section size specified
sz = qMax(sz, minimumSectionSize());
// update the minimum size for this section and count the total which we'll need
m_sectionMinSizes[i] = sz;
}
}
void RDHeaderView::resizeSectionsWithHints()
{
if(m_sectionMinSizes.isEmpty() || m_sectionStretchHints.isEmpty())
return;
QVector<int> sizes = m_sectionMinSizes;
int minsizesTotal = 0;
int stretchHintTotal = 0;
for(int i = 0; i < count() && i < sizes.count() && i < m_sectionStretchHints.count(); i++)
{
if(isSectionHidden(i))
sizes[i] = 0;
else if(m_sectionStretchHints[i] >= 0)
stretchHintTotal += m_sectionStretchHints[i];
minsizesTotal += sizes[i];
}
int available = 0;
if(orientation() == Qt::Horizontal)
available = rect().width();
else
available = rect().height();
// see if we even have any extra space to allocate
if(available > minsizesTotal)
{
// this is how much space we can allocate to stretch sections
available -= minsizesTotal;
// distribute the available space between the sections. Dividing by the total stretch tells us
// how many 'whole' multiples we can allocate:
int wholeMultiples = available / stretchHintTotal;
if(wholeMultiples > 0)
{
for(int i = 0; i < sizes.count() && i < m_sectionStretchHints.count(); i++)
{
int hint = m_sectionStretchHints[i];
if(hint > 0 && !isSectionHidden(i))
sizes[i] += wholeMultiples * hint;
}
}
available -= wholeMultiples * stretchHintTotal;
// we now have a small amount (less than stretchHintTotal) of extra space to allocate.
// we still want to assign this leftover proportional to the hints, otherwise we'd end up with a
// stair-stepping effect.
// To do this we calculate hint/total for each section then loop around adding on fractional
// components to the sizes until one is above 1, then it gets a pixel, and we keep going until
// all the remainder is allocated
QVector<float> fractions, increment;
fractions.resize(sizes.count());
increment.resize(sizes.count());
// set up increments
for(int i = 0; i < sizes.count(); i++)
{
// don't assign any space to sections with negative hints, or sections without hints, or
// hidden sections
if(i >= m_sectionStretchHints.count() || m_sectionStretchHints[i] <= 0 || isSectionHidden(i))
{
increment[i] = 0.0f;
continue;
}
increment[i] = float(m_sectionStretchHints[i]) / float(stretchHintTotal);
}
while(available > 0)
{
// loop along each section incrementing it.
for(int i = 0; i < fractions.count(); i++)
{
fractions[i] += increment[i];
// if we have a whole pixel now, assign it
if(fractions[i] > 1.0f)
{
fractions[i] -= 1.0f;
sizes[i]++;
available--;
// if we've assigned all pixels, stop
if(available == 0)
break;
}
}
}
}
resizeSections(sizes.toList());
}
void RDHeaderView::setColumnStretchHints(const QList<int> &hints)
{
if(hints.count() != count())
qCritical() << "Got" << hints.count() << "hints, but have" << count() << "columns";
m_sectionStretchHints = hints;
// we take control of the sizing, we don't currently support custom resizing AND stretchy size
// hints.
QHeaderView::setSectionResizeMode(QHeaderView::Fixed);
cacheSectionMinSizes();
resizeSectionsWithHints();
}
void RDHeaderView::setRootIndex(const QModelIndex &index)
{
QHeaderView::setRootIndex(index);
// need to enqueue this after the root index is actually processed (this function is called
// *before* the root index changes).
if(!m_sectionStretchHints.isEmpty())
{
QPointer<RDHeaderView> ptr = this;
GUIInvoke::defer(this, [this]() {
cacheSectionMinSizes();
resizeSectionsWithHints();
});
}
}
void RDHeaderView::headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast)
{
if(m_customSizing)
cacheSections();
}
void RDHeaderView::columnsInserted(const QModelIndex &parent, int first, int last)
{
if(m_customSizing)
cacheSections();
}
void RDHeaderView::rowsChanged(const QModelIndex &parent, int first, int last)
{
if(!m_sectionStretchHints.isEmpty())
{
cacheSectionMinSizes();
resizeSectionsWithHints();
}
}
void RDHeaderView::mousePressEvent(QMouseEvent *event)
{
int mousePos = event->x();
int idx = logicalIndexAt(mousePos);
if(sectionsMovable() && idx >= 0 && event->buttons() == Qt::LeftButton)
{
int secSize = sectionSize(idx);
int secPos = sectionViewportPosition(idx);
int handleWidth = style()->pixelMetric(QStyle::PM_HeaderGripMargin, 0, this);
if(secPos >= 0 && secSize > 0 && mousePos >= secPos + handleWidth &&
mousePos <= secPos + secSize - handleWidth)
{
m_movingSection = idx;
m_sectionPreview->resize(secSize, height());
QPixmap preview(m_sectionPreview->size());
preview.fill(QColor::fromRgba(qRgba(0, 0, 0, 100)));
QPainter painter(&preview);
painter.setOpacity(0.75f);
paintSection(&painter, QRect(QPoint(0, 0), m_sectionPreview->size()), idx);
painter.end();
m_sectionPreview->setPixmap(preview);
m_sectionPreviewOffset = mousePos - secPos;
m_sectionPreview->move(mousePos - m_sectionPreviewOffset, 0);
m_sectionPreview->show();
return;
}
}
if(m_customSizing)
{
m_resizeState = checkResizing(event);
m_cursorPos = QCursor::pos().x();
return QAbstractItemView::mousePressEvent(event);
}
QHeaderView::mousePressEvent(event);
}
void RDHeaderView::mouseMoveEvent(QMouseEvent *event)
{
if(m_movingSection >= 0)
{
m_sectionPreview->move(event->x() - m_sectionPreviewOffset, 0);
return;
}
if(m_customSizing)
{
if(m_resizeState.first == NoResize || m_resizeState.second < 0 ||
m_resizeState.second >= m_sections.count())
{
auto res = checkResizing(event);
bool hasCursor = testAttribute(Qt::WA_SetCursor);
if(res.first != NoResize)
{
if(!hasCursor)
setCursor(Qt::SplitHCursor);
}
else if(hasCursor)
{
unsetCursor();
}
}
else
{
int curX = QCursor::pos().x();
int delta = curX - m_cursorPos;
int idx = m_resizeState.second;
if(m_resizeState.first == LeftResize && idx > 0)
idx--;
// batch the cache update
m_suppressSectionCache = true;
int firstCol = idx;
int lastCol = idx;
// idx is the last in a group, so search backwards to see if there are neighbour sections we
// should share the resize with
while(firstCol > 0 && m_sections[firstCol - 1].group == m_sections[lastCol].group)
firstCol--;
// how much space could we lose on the columns, in total
int freeSpace = 0;
for(int col = firstCol; col <= lastCol; col++)
freeSpace += m_sections[col].size - minimumSectionSize();
int numCols = lastCol - firstCol + 1;
// spread the delta amonst the colummns
int perSectionDelta = delta / numCols;
// call resizeSection to emit the sectionResized signal but we set m_suppressSectionCache so
// we won't cache sections.
for(int col = firstCol; col <= lastCol; col++)
resizeSection(col, qMax(minimumSectionSize(), m_sections[col].size + perSectionDelta));
// if there was an uneven spread, a few pixels will remain
int remainder = delta - perSectionDelta * numCols;
// loop around for the remainder pixels, assigning them one by one to the smallest/largest
// column.
// this is inefficient but remainder is very small - at most 3.
int step = remainder < 0 ? -1 : 1;
for(int i = 0; i < qAbs(remainder); i++)
{
int chosenCol = firstCol;
for(int col = firstCol; col <= lastCol; col++)
{
if(step > 0 && m_sections[col].size < m_sections[chosenCol].size)
chosenCol = col;
else if(step < 0 && m_sections[col].size > m_sections[chosenCol].size)
chosenCol = col;
}
resizeSection(chosenCol, qMax(minimumSectionSize(), m_sections[chosenCol].size + step));
}
// only updating the cursor when the section is moving means that it becomes 'sticky'. If we
// try to size down below the minimum size and keep going then it doesn't start resizing up
// until it passes the divider again.
int appliedDelta = delta;
// if we were resizing down, at best we removed the remaining free space
if(delta < 0)
appliedDelta = qMax(delta, -freeSpace);
m_cursorPos += appliedDelta;
m_suppressSectionCache = false;
cacheSections();
}
return QAbstractItemView::mouseMoveEvent(event);
}
QHeaderView::mouseMoveEvent(event);
}
QPair<RDHeaderView::ResizeType, int> RDHeaderView::checkResizing(QMouseEvent *event)
{
int mousePos = event->x();
int idx = logicalIndexAt(mousePos);
bool hasCursor = testAttribute(Qt::WA_SetCursor);
bool cursorSet = false;
bool leftResize = idx > 0 && (m_sections[idx - 1].group != m_sections[idx].group);
bool rightResize = idx >= 0 && hasGroupTitle(idx);
if(leftResize || rightResize)
{
int secSize = sectionSize(idx);
int secPos = sectionViewportPosition(idx);
int handleWidth = style()->pixelMetric(QStyle::PM_HeaderGripMargin, 0, this);
int gapWidth = 0;
if(hasGroupGap(idx))
gapWidth = groupGapSize();
if(leftResize && secPos >= 0 && secSize > 0 && mousePos < secPos + handleWidth)
{
return qMakePair(LeftResize, idx);
}
if(rightResize && secPos >= 0 && secSize > 0 &&
mousePos > secPos + secSize - handleWidth - gapWidth)
{
return qMakePair(RightResize, idx);
}
}
return qMakePair(NoResize, -1);
}
void RDHeaderView::mouseReleaseEvent(QMouseEvent *event)
{
if(m_movingSection >= 0)
{
int mousePos = event->x();
int idx = logicalIndexAt(mousePos);
if(idx >= 0)
{
int secSize = sectionSize(idx);
int secPos = sectionPosition(idx);
int srcSection = visualIndex(m_movingSection);
int dstSection = visualIndex(idx);
if(srcSection >= 0 && dstSection >= 0 && srcSection != dstSection)
{
// the half-way point of the section decides whether we're dropping to the left
// or the right of it.
if(mousePos < secPos + secSize / 2)
{
// if we're moving from the left, place it to the left of dstSection
if(srcSection < dstSection)
moveSection(srcSection, dstSection - 1);
else
moveSection(srcSection, dstSection);
}
else
{
// if we're moving it from the right, place it to the right of dstSection
if(srcSection > dstSection)
moveSection(srcSection, dstSection + 1);
else
moveSection(srcSection, dstSection);
}
}
}
m_sectionPreview->hide();
}
m_movingSection = -1;
if(m_customSizing)
{
m_resizeState = qMakePair(NoResize, -1);
return QAbstractItemView::mouseReleaseEvent(event);
}
QHeaderView::mouseReleaseEvent(event);
}
void RDHeaderView::paintEvent(QPaintEvent *e)
{
if(!m_customSizing)
return QHeaderView::paintEvent(e);
if(count() == 0)
return;
QPainter painter(viewport());
int start = qMax(visualIndexAt(e->rect().left()), 0);
int end = visualIndexAt(e->rect().right());
if(end == -1)
end = count() - 1;
// make sure we always paint the whole header for any merged headers
while(start > 0 && !hasGroupTitle(start - 1))
start--;
while(end < m_sections.count() && !hasGroupTitle(end))
end++;
QRect accumRect;
for(int i = start; i <= end; ++i)
{
int pos = sectionViewportPosition(i);
int size = sectionSize(i);
if(!hasGroupGap(i) && pos < 0)
{
size += pos;
pos = 0;
}
// either set or accumulate this section's rect
if(accumRect.isEmpty())
accumRect.setRect(pos, 0, size, viewport()->height());
else
accumRect.setWidth(accumRect.width() + size);
if(hasGroupTitle(i))
{
painter.save();
if(accumRect.left() < m_pinnedWidth && i >= m_pinnedColumns)
accumRect.setLeft(m_pinnedWidth);
paintSection(&painter, accumRect, i);
painter.restore();
// if we have more sections to go, reset so we can accumulate the next group
if(i < end)
accumRect = QRect();
}
}
// clear the remainder of the header if there's a gap
if(accumRect.right() < e->rect().right())
{
QStyleOption opt;
opt.init(this);
opt.state |= QStyle::State_Horizontal;
opt.rect =
QRect(accumRect.right() + 1, 0, e->rect().right() - accumRect.right(), viewport()->height());
style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
}
}
void RDHeaderView::paintSection(QPainter *painter, const QRect &rect, int section) const
{
if(!m_customSizing)
return QHeaderView::paintSection(painter, rect, section);
if(!rect.isValid())
return;
QStyleOptionHeader opt;
initStyleOption(&opt);
QAbstractItemModel *m = this->model();
if(hasFocus())
opt.state |= (QStyle::State_Active | QStyle::State_HasFocus);
else
opt.state &= ~(QStyle::State_Active | QStyle::State_HasFocus);
opt.rect = rect;
opt.section = section;
opt.textAlignment = defaultAlignment();
opt.iconAlignment = Qt::AlignVCenter;
QVariant variant;
if(m_columnGroupRole)
{
variant = m->headerData(section, orientation(), m_columnGroupRole);
if(variant.isValid() && variant.canConvert<QString>())
opt.text = variant.toString();
}
if(opt.text.isEmpty())
opt.text = m->headerData(section, orientation(), Qt::DisplayRole).toString();
int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
if(textElideMode() != Qt::ElideNone)
opt.text = opt.fontMetrics.elidedText(opt.text, textElideMode(), rect.width() - margin);
if(section == 0 && section == m_sections.count() - 1)
opt.position = QStyleOptionHeader::OnlyOneSection;
else if(section == 0)
opt.position = QStyleOptionHeader::Beginning;
else if(section == m_sections.count() - 1)
opt.position = QStyleOptionHeader::End;
else
opt.position = QStyleOptionHeader::Middle;
opt.orientation = orientation();
bool prevSel = section > 0 && selectionModel()->isColumnSelected(section - 1, QModelIndex());
bool nextSel = section + 1 < m_sections.count() &&
selectionModel()->isColumnSelected(section + 1, QModelIndex());
if(prevSel && nextSel)
opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected;
else if(prevSel)
opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected;
else if(nextSel)
opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
else
opt.selectedPosition = QStyleOptionHeader::NotAdjacent;
style()->drawControl(QStyle::CE_Header, &opt, painter, this);
}
void RDHeaderView::currentChanged(const QModelIndex ¤t, const QModelIndex &old)
{
if(!m_customSizing)
return QHeaderView::currentChanged(current, old);
// not optimal at all
if(current != old)
{
QRect r = viewport()->rect();
if(old.isValid())
{
QRect rect = r;
if(orientation() == Qt::Horizontal)
{
rect.setLeft(sectionViewportPosition(old.column()));
rect.setWidth(sectionSize(old.column()));
}
else
{
rect.setTop(sectionViewportPosition(old.column()));
rect.setHeight(sectionSize(old.column()));
}
viewport()->update(rect);
}
if(current.isValid())
{
QRect rect = r;
if(orientation() == Qt::Horizontal)
{
rect.setLeft(sectionViewportPosition(current.column()));
rect.setWidth(sectionSize(current.column()));
}
else
{
rect.setTop(sectionViewportPosition(current.column()));
rect.setHeight(sectionSize(current.column()));
}
viewport()->update(rect);
}
}
}
void RDHeaderView::updateGeometries()
{
if(!m_sectionStretchHints.isEmpty())
resizeSectionsWithHints();
QHeaderView::updateGeometries();
}
|