2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
41 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
42 case KStandardItemListView::IconsLayout
:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
46 case KStandardItemListView::CompactLayout
:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
50 case KStandardItemListView::DetailsLayout
:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
60 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
62 const KItemListView
* view
) const
64 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
65 const KItemListStyleOption
& option
= view
->styleOption();
67 const QString text
= roleText(role
, values
);
68 qreal width
= KStandardItemListWidget::columnPadding(option
);
70 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
71 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
73 if (role
== "rating") {
74 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
76 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
77 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
79 width
+= fontMetrics
.horizontalAdvance(text
);
82 if (view
->supportsItemExpanding()) {
83 // Increase the width by the expansion-toggle and the current expansion level
84 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
85 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
86 width
+= (expandedParentsCount
+ 1) * height
;
89 // Increase the width by the required space for the icon
90 width
+= option
.padding
* 2 + option
.iconSize
;
97 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
* view
) const
99 return view
->model()->data(index
).value("text").toString();
102 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
* view
) const
109 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
110 const QHash
<QByteArray
, QVariant
>& values
) const
112 if (role
== "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
116 return values
.value(role
).toString();
119 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
& baseFont
) const
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
126 const KItemListStyleOption
& option
= view
->styleOption();
127 const QFont
& normalFont
= option
.font
;
128 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
130 const qreal itemWidth
= view
->itemSize().width();
131 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
132 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
133 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
135 const QFont linkFont
= customizedFontForLinks(normalFont
);
137 QTextOption
textOption(Qt::AlignHCenter
);
138 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
140 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
141 if (logicalHeightHints
.at(index
).first
> 0.0) {
145 // If the current item is a link, we use the customized link font instead of the normal font.
146 const QFont
& font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
148 const QString
& text
= KStringHandler::preProcessWrap(itemText(index
, view
));
150 // Calculate the number of lines required for wrapping the name
151 qreal textHeight
= 0;
152 QTextLayout
layout(text
, font
);
153 layout
.setTextOption(textOption
);
154 layout
.beginLayout();
157 bool isElided
= false;
158 while ((line
= layout
.createLine()).isValid()) {
159 line
.setLineWidth(maxWidth
);
160 line
.naturalTextWidth();
161 textHeight
+= line
.height();
164 if (lineCount
== option
.maxTextLines
) {
165 isElided
= layout
.createLine().isValid();
171 // Add one line for each additional information
172 textHeight
+= additionalRolesSpacing
;
174 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
175 logicalHeightHints
[index
].second
= isElided
;
178 logicalWidthHint
= itemWidth
;
181 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
183 const KItemListStyleOption
& option
= view
->styleOption();
184 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
185 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
187 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
188 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
189 const qreal maxWidth
= option
.maxTextWidth
;
190 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
191 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
193 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
195 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
196 if (logicalHeightHints
.at(index
).first
> 0.0) {
200 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
201 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
203 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
204 // to show all roles without horizontal clipping.
205 qreal maximumRequiredWidth
= 0.0;
207 if (showOnlyTextRole
) {
208 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
210 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
211 for (const QByteArray
& role
: visibleRoles
) {
212 const QString
& text
= roleText(role
, values
);
213 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
214 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
218 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
219 if (maxWidth
> 0 && width
> maxWidth
) {
223 logicalHeightHints
[index
].first
= width
;
226 logicalWidthHint
= height
;
229 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
231 const KItemListStyleOption
& option
= view
->styleOption();
234 if (option
.iconSize
>= KIconLoader::SizeEnormous
) {
236 } else if (option
.iconSize
>= KIconLoader::SizeHuge
) {
238 } else if (option
.iconSize
>= KIconLoader::SizeLarge
) {
240 } else if (option
.iconSize
>= KIconLoader::SizeMedium
) {
242 } else if (option
.iconSize
>= KIconLoader::SizeSmallMedium
) {
246 const qreal contentHeight
= qMax
<qreal
>(option
.iconSize
, zoomLevel
* option
.fontMetrics
.height());
247 logicalHeightHints
.fill(std::make_pair(contentHeight
+ 2 * option
.padding
, false));
248 logicalWidthHint
= -1.0;
251 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
252 KItemListWidget(informant
, parent
),
257 m_customizedFontMetrics(m_customizedFont
),
258 m_isExpandable(false),
259 m_supportsItemExpanding(false),
261 m_dirtyContent(true),
262 m_dirtyContentRoles(),
263 m_layout(IconsLayout
),
266 m_scaledPixmapSize(),
271 m_sortedVisibleRoles(),
274 m_additionalInfoTextColor(),
277 m_roleEditor(nullptr),
278 m_oldRoleEditor(nullptr)
282 KStandardItemListWidget::~KStandardItemListWidget()
284 qDeleteAll(m_textInfo
);
288 m_roleEditor
->deleteLater();
291 if (m_oldRoleEditor
) {
292 m_oldRoleEditor
->deleteLater();
296 void KStandardItemListWidget::setLayout(Layout layout
)
298 if (m_layout
!= layout
) {
300 m_dirtyLayout
= true;
301 updateAdditionalInfoTextColor();
306 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
311 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
) {
312 if (m_highlightEntireRow
!= highlightEntireRow
) {
313 m_highlightEntireRow
= highlightEntireRow
;
314 m_dirtyLayout
= true;
319 bool KStandardItemListWidget::highlightEntireRow() const {
320 return m_highlightEntireRow
;
323 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
325 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
326 m_supportsItemExpanding
= supportsItemExpanding
;
327 m_dirtyLayout
= true;
332 bool KStandardItemListWidget::supportsItemExpanding() const
334 return m_supportsItemExpanding
;
337 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
339 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
341 KItemListWidget::paint(painter
, option
, widget
);
343 if (!m_expansionArea
.isEmpty()) {
344 drawSiblingsInformation(painter
);
347 const KItemListStyleOption
& itemListStyleOption
= styleOption();
348 if (isHovered() && !m_pixmap
.isNull()) {
349 if (hoverOpacity() < 1.0) {
351 * Linear interpolation between m_pixmap and m_hoverPixmap.
353 * Note that this cannot be achieved by painting m_hoverPixmap over
354 * m_pixmap, even if the opacities are adjusted. For details see
355 * https://git.reviewboard.kde.org/r/109614/
357 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
358 QPixmap
pixmap1(m_pixmap
.size());
359 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
360 pixmap1
.fill(Qt::transparent
);
362 QPainter
p(&pixmap1
);
363 p
.setOpacity(1.0 - hoverOpacity());
364 p
.drawPixmap(0, 0, m_pixmap
);
367 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
368 QPixmap
pixmap2(pixmap1
.size());
369 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
370 pixmap2
.fill(Qt::transparent
);
372 QPainter
p(&pixmap2
);
373 p
.setOpacity(hoverOpacity());
374 p
.drawPixmap(0, 0, m_hoverPixmap
);
377 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
378 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
379 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
381 QPainter
p(&pixmap1
);
382 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
383 p
.drawPixmap(0, 0, pixmap2
);
386 // Finally paint pixmap1 on the widget
387 drawPixmap(painter
, pixmap1
);
389 drawPixmap(painter
, m_hoverPixmap
);
391 } else if (!m_pixmap
.isNull()) {
392 drawPixmap(painter
, m_pixmap
);
395 painter
->setFont(m_customizedFont
);
396 painter
->setPen(textColor());
397 const TextInfo
* textInfo
= m_textInfo
.value("text");
400 // It seems that we can end up here even if m_textInfo does not contain
401 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
402 // this can only happen if the index is negative. This can happen when
403 // the item is about to be removed, see KItemListView::slotItemsRemoved().
404 // TODO: try to reproduce the crash and find a better fix.
408 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
410 bool clipAdditionalInfoBounds
= false;
411 if (m_supportsItemExpanding
) {
412 // Prevent a possible overlapping of the additional-information texts
413 // with the icon. This can happen if the user has minimized the width
414 // of the name-column to a very small value.
415 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
416 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
417 clipAdditionalInfoBounds
= true;
419 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
423 painter
->setPen(m_additionalInfoTextColor
);
424 painter
->setFont(m_customizedFont
);
426 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
427 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
428 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
431 if (!m_rating
.isNull()) {
432 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
433 QPointF pos
= ratingTextInfo
->pos
;
434 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
435 if (align
& Qt::AlignHCenter
) {
436 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
438 painter
->drawPixmap(pos
, m_rating
);
441 if (clipAdditionalInfoBounds
) {
445 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
446 painter
->setBrush(Qt::NoBrush
);
447 painter
->setPen(Qt::green
);
448 painter
->drawRect(m_iconRect
);
450 painter
->setPen(Qt::blue
);
451 painter
->drawRect(m_textRect
);
453 painter
->setPen(Qt::red
);
454 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
455 painter
->drawRect(rect());
459 QRectF
KStandardItemListWidget::iconRect() const
461 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
465 QRectF
KStandardItemListWidget::textRect() const
467 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
471 QRectF
KStandardItemListWidget::textFocusRect() const
473 // In the compact- and details-layout a larger textRect() is returned to be aligned
474 // with the iconRect(). This is useful to have a larger selection/hover-area
475 // when having a quite large icon size but only one line of text. Still the
476 // focus rectangle should be shown as narrow as possible around the text.
478 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
481 case CompactLayout
: {
482 QRectF rect
= m_textRect
;
483 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
484 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
485 rect
.setTop(topText
->pos
.y());
486 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
490 case DetailsLayout
: {
491 QRectF rect
= m_textRect
;
492 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
493 rect
.setTop(textInfo
->pos
.y());
494 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
496 const KItemListStyleOption
& option
= styleOption();
497 if (option
.extendedSelectionRegion
) {
498 const QString text
= textInfo
->staticText
.text();
499 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
512 QRectF
KStandardItemListWidget::selectionRect() const
514 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
521 case DetailsLayout
: {
522 const int padding
= styleOption().padding
;
523 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
524 QRectF result
= adjustedIconRect
| m_textRect
;
525 if (m_highlightEntireRow
) {
526 result
.setRight(m_columnWidthSum
+ leadingPadding());
539 QRectF
KStandardItemListWidget::expansionToggleRect() const
541 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
542 return m_isExpandable
? m_expansionArea
: QRectF();
545 QRectF
KStandardItemListWidget::selectionToggleRect() const
547 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
549 const int iconHeight
= styleOption().iconSize
;
551 int toggleSize
= KIconLoader::SizeSmall
;
552 if (iconHeight
>= KIconLoader::SizeEnormous
) {
553 toggleSize
= KIconLoader::SizeMedium
;
554 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
555 toggleSize
= KIconLoader::SizeSmallMedium
;
558 QPointF pos
= iconRect().topLeft();
560 // If the selection toggle has a very small distance to the
561 // widget borders, the size of the selection toggle will get
562 // increased to prevent an accidental clicking of the item
563 // when trying to hit the toggle.
564 const int widgetHeight
= size().height();
565 const int widgetWidth
= size().width();
566 const int minMargin
= 2;
568 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
569 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
570 toggleSize
= widgetHeight
;
573 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
574 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
575 toggleSize
= widgetWidth
;
579 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
582 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
585 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
586 if (m_layout
!= DetailsLayout
) {
590 // Only return the content of the text-column as pixmap
591 const int leftClip
= m_pixmapPos
.x();
593 const TextInfo
* textInfo
= m_textInfo
.value("text");
594 const int rightClip
= textInfo
->pos
.x() +
595 textInfo
->staticText
.size().width() +
596 2 * styleOption().padding
;
598 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
599 clippedPixmap
.fill(Qt::transparent
);
601 QPainter
painter(&clippedPixmap
);
602 painter
.drawPixmap(-leftClip
, 0, pixmap
);
604 return clippedPixmap
;
608 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
610 return new KStandardItemListWidgetInformant();
613 void KStandardItemListWidget::invalidateCache()
615 m_dirtyLayout
= true;
616 m_dirtyContent
= true;
619 void KStandardItemListWidget::invalidateIconCache()
621 m_dirtyContent
= true;
622 m_dirtyContentRoles
.insert("iconPixmap");
623 m_dirtyContentRoles
.insert("iconOverlays");
626 void KStandardItemListWidget::refreshCache()
630 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
636 bool KStandardItemListWidget::isHidden() const
641 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
646 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
648 return QPalette::Text
;
651 void KStandardItemListWidget::setTextColor(const QColor
& color
)
653 if (color
!= m_customTextColor
) {
654 m_customTextColor
= color
;
655 updateAdditionalInfoTextColor();
660 QColor
KStandardItemListWidget::textColor() const
664 return m_additionalInfoTextColor
;
665 } else if (m_customTextColor
.isValid()) {
666 return m_customTextColor
;
670 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
671 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
672 return styleOption().palette
.color(group
, role
);
675 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
678 m_dirtyContent
= true;
682 QPixmap
KStandardItemListWidget::overlay() const
688 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
689 const QHash
<QByteArray
, QVariant
>& values
) const
691 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
694 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
695 const QSet
<QByteArray
>& roles
)
699 m_dirtyContent
= true;
701 QSet
<QByteArray
> dirtyRoles
;
702 if (roles
.isEmpty()) {
703 const auto visibleRoles
= this->visibleRoles();
704 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
709 // The URL might have changed (i.e., if the sort order of the items has
710 // been changed). Therefore, the "is cut" state must be updated.
711 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
712 const QUrl itemUrl
= data().value("url").toUrl();
713 m_isCut
= clipboard
->isCut(itemUrl
);
715 // The icon-state might depend from other roles and hence is
716 // marked as dirty whenever a role has been changed
717 dirtyRoles
.insert("iconPixmap");
718 dirtyRoles
.insert("iconName");
720 QSetIterator
<QByteArray
> it(dirtyRoles
);
721 while (it
.hasNext()) {
722 const QByteArray
& role
= it
.next();
723 m_dirtyContentRoles
.insert(role
);
727 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
728 const QList
<QByteArray
>& previous
)
731 m_sortedVisibleRoles
= current
;
732 m_dirtyLayout
= true;
735 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
742 m_dirtyLayout
= true;
745 void KStandardItemListWidget::leadingPaddingChanged(qreal padding
) {
747 m_dirtyLayout
= true;
750 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
751 const KItemListStyleOption
& previous
)
755 updateAdditionalInfoTextColor();
756 m_dirtyLayout
= true;
759 void KStandardItemListWidget::hoveredChanged(bool hovered
)
762 m_dirtyLayout
= true;
765 void KStandardItemListWidget::selectedChanged(bool selected
)
768 updateAdditionalInfoTextColor();
769 m_dirtyContent
= true;
772 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
776 m_dirtyLayout
= true;
779 int KStandardItemListWidget::selectionLength(const QString
& text
) const
781 return text
.length();
784 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
788 QGraphicsView
* parent
= scene()->views()[0];
789 if (current
.isEmpty() || !parent
|| current
!= "text") {
791 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
793 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
794 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
795 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
796 this, &KStandardItemListWidget::slotRoleEditingFinished
);
798 if (m_oldRoleEditor
) {
799 m_oldRoleEditor
->deleteLater();
801 m_oldRoleEditor
= m_roleEditor
;
802 m_roleEditor
->hide();
803 m_roleEditor
= nullptr;
808 Q_ASSERT(!m_roleEditor
);
810 const TextInfo
* textInfo
= m_textInfo
.value("text");
812 m_roleEditor
= new KItemListRoleEditor(parent
);
813 m_roleEditor
->setRole(current
);
814 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
815 m_roleEditor
->setFont(styleOption().font
);
817 const QString text
= data().value(current
).toString();
818 m_roleEditor
->setPlainText(text
);
820 QTextOption textOption
= textInfo
->staticText
.textOption();
821 m_roleEditor
->document()->setDefaultTextOption(textOption
);
823 const int textSelectionLength
= selectionLength(text
);
825 if (textSelectionLength
> 0) {
826 QTextCursor cursor
= m_roleEditor
->textCursor();
827 cursor
.movePosition(QTextCursor::StartOfBlock
);
828 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
829 m_roleEditor
->setTextCursor(cursor
);
832 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
833 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
834 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
835 this, &KStandardItemListWidget::slotRoleEditingFinished
);
837 // Adjust the geometry of the editor
838 QRectF rect
= roleEditingRect(current
);
839 const int frameWidth
= m_roleEditor
->frameWidth();
840 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
841 rect
.translate(pos());
842 if (rect
.right() > parent
->width()) {
843 rect
.setWidth(parent
->width() - rect
.left());
845 m_roleEditor
->setGeometry(rect
.toRect());
846 m_roleEditor
->show();
847 m_roleEditor
->setFocus();
850 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
853 setEditedRole(QByteArray());
854 Q_ASSERT(!m_roleEditor
);
857 KItemListWidget::resizeEvent(event
);
859 m_dirtyLayout
= true;
862 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
864 KItemListWidget::showEvent(event
);
866 // Listen to changes of the clipboard to mark the item as cut/uncut
867 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
869 const QUrl itemUrl
= data().value("url").toUrl();
870 m_isCut
= clipboard
->isCut(itemUrl
);
872 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
873 this, &KStandardItemListWidget::slotCutItemsChanged
);
876 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
878 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
879 this, &KStandardItemListWidget::slotCutItemsChanged
);
881 KItemListWidget::hideEvent(event
);
884 bool KStandardItemListWidget::event(QEvent
*event
)
886 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
887 || event
->type() == QEvent::PaletteChange
) {
888 m_dirtyContent
= true;
891 return KItemListWidget::event(event
);
894 void KStandardItemListWidget::finishRoleEditing()
896 if (!editedRole().isEmpty() && m_roleEditor
) {
897 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
901 void KStandardItemListWidget::slotCutItemsChanged()
903 const QUrl itemUrl
= data().value("url").toUrl();
904 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
905 if (m_isCut
!= isCut
) {
907 m_pixmap
= QPixmap();
908 m_dirtyContent
= true;
913 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
914 const QVariant
& value
)
917 Q_EMIT
roleEditingCanceled(index(), role
, value
);
918 setEditedRole(QByteArray());
921 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
922 const QVariant
& value
)
925 Q_EMIT
roleEditingFinished(index(), role
, value
);
926 setEditedRole(QByteArray());
929 void KStandardItemListWidget::triggerCacheRefreshing()
931 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
937 const QHash
<QByteArray
, QVariant
> values
= data();
938 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
939 m_isHidden
= isHidden();
940 m_customizedFont
= customizedFont(styleOption().font
);
941 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
942 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(),
943 qreal(), [this](qreal sum
, const auto &role
){ return sum
+ columnWidth(role
); });
945 updateExpansionArea();
950 m_dirtyLayout
= false;
951 m_dirtyContent
= false;
952 m_dirtyContentRoles
.clear();
955 void KStandardItemListWidget::updateExpansionArea()
957 if (m_supportsItemExpanding
) {
958 const QHash
<QByteArray
, QVariant
> values
= data();
959 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
960 if (expandedParentsCount
>= 0) {
961 const KItemListStyleOption
& option
= styleOption();
962 const qreal widgetHeight
= size().height();
963 const qreal inc
= (widgetHeight
- option
.iconSize
) / 2;
964 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
966 const qreal xPadding
= m_highlightEntireRow
? leadingPadding() : 0;
967 m_expansionArea
= QRectF(xPadding
+ x
, y
, option
.iconSize
, option
.iconSize
);
972 m_expansionArea
= QRectF();
975 void KStandardItemListWidget::updatePixmapCache()
977 // Precondition: Requires already updated m_textPos values to calculate
978 // the remaining height when the alignment is vertical.
980 const QSizeF widgetSize
= size();
981 const bool iconOnTop
= (m_layout
== IconsLayout
);
982 const KItemListStyleOption
& option
= styleOption();
983 const qreal padding
= option
.padding
;
985 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
986 const int maxIconHeight
= option
.iconSize
;
988 const QHash
<QByteArray
, QVariant
> values
= data();
990 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
991 if (!updatePixmap
&& m_dirtyContent
) {
992 updatePixmap
= m_dirtyContentRoles
.isEmpty()
993 || m_dirtyContentRoles
.contains("iconPixmap")
994 || m_dirtyContentRoles
.contains("iconName")
995 || m_dirtyContentRoles
.contains("iconOverlays");
999 m_pixmap
= QPixmap();
1001 int sequenceIndex
= hoverSequenceIndex();
1003 if (values
.contains("hoverSequencePixmaps")) {
1004 // Use one of the hover sequence pixmaps instead of the default
1007 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1009 if (values
.contains("hoverSequenceWraparoundPoint")) {
1010 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1012 sequenceIndex
%= static_cast<int>(wap
);
1016 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
1018 if (loadedIndex
!= 0) {
1019 m_pixmap
= pixmaps
[loadedIndex
];
1023 if (m_pixmap
.isNull()) {
1024 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1027 if (m_pixmap
.isNull()) {
1028 // Use the icon that fits to the MIME-type
1029 QString iconName
= values
["iconName"].toString();
1030 if (iconName
.isEmpty()) {
1031 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1032 // use a generic icon as fallback
1033 iconName
= QStringLiteral("unknown");
1035 const QStringList overlays
= values
["iconOverlays"].toStringList();
1036 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1038 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1039 // A custom pixmap has been applied. Assure that the pixmap
1040 // is scaled to the maximum available size.
1041 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1044 if (m_pixmap
.isNull()) {
1045 m_hoverPixmap
= QPixmap();
1050 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1051 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1055 KIconEffect::semiTransparent(m_pixmap
);
1058 if (m_layout
== IconsLayout
&& isSelected()) {
1059 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1060 QImage image
= m_pixmap
.toImage();
1061 if (image
.isNull()) {
1062 m_hoverPixmap
= QPixmap();
1065 KIconEffect::colorize(image
, color
, 0.8f
);
1066 m_pixmap
= QPixmap::fromImage(image
);
1070 if (!m_overlay
.isNull()) {
1071 QPainter
painter(&m_pixmap
);
1072 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1075 int scaledIconSize
= 0;
1077 const TextInfo
* textInfo
= m_textInfo
.value("text");
1078 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1080 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1081 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1082 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1083 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1086 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1087 const int maxScaledIconHeight
= scaledIconSize
;
1089 m_scaledPixmapSize
= m_pixmap
.size();
1090 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1091 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1094 // Center horizontally and align on bottom within the icon-area
1095 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1096 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1098 // Center horizontally and vertically within the icon-area
1099 const TextInfo
* textInfo
= m_textInfo
.value("text");
1100 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1101 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1103 // Derive icon's vertical center from the center of the text frame, including
1104 // any necessary adjustment if the font's midline is offset from the frame center
1105 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1106 - m_customizedFontMetrics
.descent()
1107 - m_customizedFontMetrics
.capHeight() / 2.0;
1108 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1112 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1114 // Prepare the pixmap that is used when the item gets hovered
1116 m_hoverPixmap
= m_pixmap
;
1117 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1118 // In the KIconLoader terminology, active = hover.
1119 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1120 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1122 m_hoverPixmap
= m_pixmap
;
1124 } else if (hoverOpacity() <= 0.0) {
1125 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1126 m_hoverPixmap
= QPixmap();
1130 void KStandardItemListWidget::updateTextsCache()
1132 QTextOption textOption
;
1135 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1136 textOption
.setAlignment(Qt::AlignHCenter
);
1140 textOption
.setAlignment(Qt::AlignLeft
);
1141 textOption
.setWrapMode(QTextOption::NoWrap
);
1148 qDeleteAll(m_textInfo
);
1150 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1151 TextInfo
* textInfo
= new TextInfo();
1152 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1153 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1154 textInfo
->staticText
.setTextOption(textOption
);
1155 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1159 case IconsLayout
: updateIconsLayoutTextCache(); break;
1160 case CompactLayout
: updateCompactLayoutTextCache(); break;
1161 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1162 default: Q_ASSERT(false); break;
1165 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1166 if (ratingTextInfo
) {
1167 // The text of the rating-role has been set to empty to get
1168 // replaced by a rating-image showing the rating as stars.
1169 const KItemListStyleOption
& option
= styleOption();
1170 QSizeF ratingSize
= preferredRatingSize(option
);
1172 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1173 ? columnWidth("rating") - columnPadding(option
)
1175 if (ratingSize
.width() > availableWidth
) {
1176 ratingSize
.rwidth() = availableWidth
;
1178 const qreal dpr
= qApp
->devicePixelRatio();
1179 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1180 m_rating
.setDevicePixelRatio(dpr
);
1181 m_rating
.fill(Qt::transparent
);
1183 QPainter
painter(&m_rating
);
1184 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1185 const int rating
= data().value("rating").toInt();
1186 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1187 } else if (!m_rating
.isNull()) {
1188 m_rating
= QPixmap();
1192 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1194 const auto extensionIndex
= text
.lastIndexOf('.');
1195 if (extensionIndex
!= -1) {
1196 // has file extension
1197 const auto extensionLength
= text
.length() - extensionIndex
;
1198 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1199 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1200 // if we have room to display the file extension and the extension is not too long
1201 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1203 elidingWidth
- extensionWidth
);
1204 ret
.append(text
.rightRef(extensionLength
));
1208 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1212 void KStandardItemListWidget::updateIconsLayoutTextCache()
1219 // might get wrapped above
1221 // Additional role 1
1222 // Additional role 2
1224 const QHash
<QByteArray
, QVariant
> values
= data();
1226 const KItemListStyleOption
& option
= styleOption();
1227 const qreal padding
= option
.padding
;
1228 const qreal maxWidth
= size().width() - 2 * padding
;
1229 const qreal widgetHeight
= size().height();
1230 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1232 // Initialize properties for the "text" role. It will be used as anchor
1233 // for initializing the position of the other roles.
1234 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1235 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1236 nameTextInfo
->staticText
.setText(nameText
);
1238 // Calculate the number of lines required for the name and the required width
1239 qreal nameWidth
= 0;
1240 qreal nameHeight
= 0;
1243 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1244 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1245 layout
.beginLayout();
1246 int nameLineIndex
= 0;
1247 while ((line
= layout
.createLine()).isValid()) {
1248 line
.setLineWidth(maxWidth
);
1249 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1250 nameHeight
+= line
.height();
1253 if (nameLineIndex
== option
.maxTextLines
) {
1254 // The maximum number of textlines has been reached. If this is
1255 // the case provide an elided text if necessary.
1256 const int textLength
= line
.textStart() + line
.textLength();
1257 if (textLength
< nameText
.length()) {
1258 // Elide the last line of the text
1259 qreal elidingWidth
= maxWidth
;
1260 qreal lastLineWidth
;
1262 QString lastTextLine
= nameText
.mid(line
.textStart());
1263 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1264 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1265 nameTextInfo
->staticText
.setText(elidedText
);
1267 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1269 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1270 // to avoid problems related to different width calculation code paths
1271 // within Qt. (see bug 337104)
1272 elidingWidth
-= 1.0;
1273 } while (lastLineWidth
> maxWidth
);
1275 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1282 // Use one line for each additional information
1283 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1284 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1285 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1287 additionalRolesCount
* lineSpacing
-
1289 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1290 nameTextInfo
->pos
.y(),
1294 // Calculate the position for each additional information
1295 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1296 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1297 if (role
== "text") {
1301 const QString text
= roleText(role
, values
);
1302 TextInfo
* textInfo
= m_textInfo
.value(role
);
1303 textInfo
->staticText
.setText(text
);
1305 qreal requiredWidth
= 0;
1307 QTextLayout
layout(text
, m_customizedFont
);
1308 QTextOption textOption
;
1309 textOption
.setWrapMode(QTextOption::NoWrap
);
1310 layout
.setTextOption(textOption
);
1312 layout
.beginLayout();
1313 QTextLine textLine
= layout
.createLine();
1314 if (textLine
.isValid()) {
1315 textLine
.setLineWidth(maxWidth
);
1316 requiredWidth
= textLine
.naturalTextWidth();
1317 if (requiredWidth
> maxWidth
) {
1318 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1319 textInfo
->staticText
.setText(elidedText
);
1320 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1321 } else if (role
== "rating") {
1322 // Use the width of the rating pixmap, because the rating text is empty.
1323 requiredWidth
= m_rating
.width();
1328 textInfo
->pos
= QPointF(padding
, y
);
1329 textInfo
->staticText
.setTextWidth(maxWidth
);
1331 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1332 m_textRect
|= textRect
;
1337 // Add a padding to the text rectangle
1338 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1341 void KStandardItemListWidget::updateCompactLayoutTextCache()
1343 // +------+ Name role
1344 // | Icon | Additional role 1
1345 // +------+ Additional role 2
1347 const QHash
<QByteArray
, QVariant
> values
= data();
1349 const KItemListStyleOption
& option
= styleOption();
1350 const qreal widgetHeight
= size().height();
1351 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1352 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1353 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1355 qreal maximumRequiredTextWidth
= 0;
1356 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1357 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1358 const qreal maxWidth
= size().width() - x
- option
.padding
;
1359 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1360 const QString text
= roleText(role
, values
);
1361 TextInfo
* textInfo
= m_textInfo
.value(role
);
1362 textInfo
->staticText
.setText(text
);
1364 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1365 if (requiredWidth
> maxWidth
) {
1366 requiredWidth
= maxWidth
;
1367 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1368 textInfo
->staticText
.setText(elidedText
);
1371 textInfo
->pos
= QPointF(x
, y
);
1372 textInfo
->staticText
.setTextWidth(maxWidth
);
1374 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1379 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1382 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1384 // Precondition: Requires already updated m_expansionArea
1385 // to determine the left position.
1388 // | Icon | Name role Additional role 1 Additional role 2
1390 m_textRect
= QRectF();
1392 const KItemListStyleOption
& option
= styleOption();
1393 const QHash
<QByteArray
, QVariant
> values
= data();
1395 const qreal widgetHeight
= size().height();
1396 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1397 const int fontHeight
= m_customizedFontMetrics
.height();
1399 const qreal columnWidthInc
= columnPadding(option
);
1400 qreal firstColumnInc
= scaledIconSize
;
1401 if (m_supportsItemExpanding
) {
1402 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1404 firstColumnInc
+= option
.padding
+ leadingPadding();
1407 qreal x
= firstColumnInc
;
1408 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1410 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1411 QString text
= roleText(role
, values
);
1413 // Elide the text in case it does not fit into the available column-width
1414 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1415 const qreal roleWidth
= columnWidth(role
);
1416 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1418 const bool isTextRole
= (role
== "text");
1420 availableTextWidth
-= firstColumnInc
- leadingPadding();
1423 if (requiredWidth
> availableTextWidth
) {
1424 text
= elideRightKeepExtension(text
, availableTextWidth
);
1425 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1428 TextInfo
* textInfo
= m_textInfo
.value(role
);
1429 textInfo
->staticText
.setText(text
);
1430 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1434 const qreal textWidth
= option
.extendedSelectionRegion
1435 ? size().width() - textInfo
->pos
.x()
1436 : requiredWidth
+ 2 * option
.padding
;
1437 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1438 textWidth
, size().height());
1440 // The column after the name should always be aligned on the same x-position independent
1441 // from the expansion-level shown in the name column
1442 x
-= firstColumnInc
- leadingPadding();
1443 } else if (isRoleRightAligned(role
)) {
1444 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1449 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1452 if (m_customTextColor
.isValid()) {
1453 c1
= m_customTextColor
;
1454 } else if (isSelected()) {
1455 // The detail text colour needs to match the main text (HighlightedText) for the same level
1456 // of readability. We short circuit early here to avoid interpolating with another colour.
1457 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1460 c1
= styleOption().palette
.text().color();
1463 // For the color of the additional info the inactive text color
1464 // is not used as this might lead to unreadable text for some color schemes. Instead
1465 // the text color c1 is slightly mixed with the background color.
1466 const QColor c2
= styleOption().palette
.base().color();
1468 const int p2
= 100 - p1
;
1469 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1470 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1471 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1474 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1476 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1477 QPixmap scaledPixmap
= pixmap
;
1478 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1479 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1480 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1482 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1483 painter
->setPen(Qt::blue
);
1484 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1487 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1491 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1493 const int siblingSize
= size().height();
1494 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1495 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1497 bool isItemSibling
= true;
1499 const QBitArray siblings
= siblingsInformation();
1500 QStyleOption option
;
1501 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1502 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1503 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1504 option
.rect
= siblingRect
;
1505 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1506 if (isItemSibling
) {
1507 option
.state
|= QStyle::State_Item
;
1508 if (m_isExpandable
) {
1509 option
.state
|= QStyle::State_Children
;
1511 if (data().value("isExpanded").toBool()) {
1512 option
.state
|= QStyle::State_Open
;
1514 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1515 isItemSibling
= false;
1517 option
.palette
.setColor(QPalette::Text
, normalColor
);
1520 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1522 siblingRect
.translate(-siblingRect
.width(), 0);
1526 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1528 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1533 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1534 if (m_layout
== DetailsLayout
) {
1535 rect
.setWidth(columnWidth(role
) - rect
.x());
1541 void KStandardItemListWidget::closeRoleEditor()
1543 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1544 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1545 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1546 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1548 if (m_roleEditor
->hasFocus()) {
1549 // If the editing was not ended by a FocusOut event, we have
1550 // to transfer the keyboard focus back to the KItemListContainer.
1551 scene()->views()[0]->parentWidget()->setFocus();
1554 if (m_oldRoleEditor
) {
1555 m_oldRoleEditor
->deleteLater();
1557 m_oldRoleEditor
= m_roleEditor
;
1558 m_roleEditor
->hide();
1559 m_roleEditor
= nullptr;
1562 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1564 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1566 size
*= qApp
->devicePixelRatio();
1568 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1571 if (!QPixmapCache::find(key
, &pixmap
)) {
1572 QIcon icon
= QIcon::fromTheme(name
);
1573 if (icon
.isNull()) {
1577 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1578 icon
= fallbackIcon
;
1581 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1582 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1583 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1586 // Strangely KFileItem::overlays() returns empty string-values, so
1587 // we need to check first whether an overlay must be drawn at all.
1588 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1589 // assumes that an overlay will be drawn and has some additional
1591 for (const QString
& overlay
: overlays
) {
1592 if (!overlay
.isEmpty()) {
1593 int state
= KIconLoader::DefaultState
;
1599 state
= KIconLoader::ActiveState
;
1601 case QIcon::Disabled
:
1602 state
= KIconLoader::DisabledState
;
1604 case QIcon::Selected
:
1605 state
= KIconLoader::SelectedState
;
1609 // There is at least one overlay, draw all overlays above m_pixmap
1610 // and cancel the check
1611 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1616 QPixmapCache::insert(key
, pixmap
);
1618 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1623 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1625 const qreal height
= option
.fontMetrics
.ascent();
1626 return QSizeF(height
* 5, height
);
1629 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1631 return option
.padding
* 6;