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();
232 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
233 logicalHeightHints
.fill(std::make_pair(height
, false));
234 logicalWidthHint
= -1.0;
237 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
238 KItemListWidget(informant
, parent
),
243 m_customizedFontMetrics(m_customizedFont
),
244 m_isExpandable(false),
245 m_supportsItemExpanding(false),
247 m_dirtyContent(true),
248 m_dirtyContentRoles(),
249 m_layout(IconsLayout
),
252 m_scaledPixmapSize(),
257 m_sortedVisibleRoles(),
260 m_additionalInfoTextColor(),
263 m_roleEditor(nullptr),
264 m_oldRoleEditor(nullptr)
268 KStandardItemListWidget::~KStandardItemListWidget()
270 qDeleteAll(m_textInfo
);
274 m_roleEditor
->deleteLater();
277 if (m_oldRoleEditor
) {
278 m_oldRoleEditor
->deleteLater();
282 void KStandardItemListWidget::setLayout(Layout layout
)
284 if (m_layout
!= layout
) {
286 m_dirtyLayout
= true;
287 updateAdditionalInfoTextColor();
292 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
297 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
) {
298 if (m_highlightEntireRow
!= highlightEntireRow
) {
299 m_highlightEntireRow
= highlightEntireRow
;
300 m_dirtyLayout
= true;
305 bool KStandardItemListWidget::highlightEntireRow() const {
306 return m_highlightEntireRow
;
309 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
311 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
312 m_supportsItemExpanding
= supportsItemExpanding
;
313 m_dirtyLayout
= true;
318 bool KStandardItemListWidget::supportsItemExpanding() const
320 return m_supportsItemExpanding
;
323 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
325 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
327 KItemListWidget::paint(painter
, option
, widget
);
329 if (!m_expansionArea
.isEmpty()) {
330 drawSiblingsInformation(painter
);
333 const KItemListStyleOption
& itemListStyleOption
= styleOption();
334 if (isHovered() && !m_pixmap
.isNull()) {
335 if (hoverOpacity() < 1.0) {
337 * Linear interpolation between m_pixmap and m_hoverPixmap.
339 * Note that this cannot be achieved by painting m_hoverPixmap over
340 * m_pixmap, even if the opacities are adjusted. For details see
341 * https://git.reviewboard.kde.org/r/109614/
343 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
344 QPixmap
pixmap1(m_pixmap
.size());
345 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
346 pixmap1
.fill(Qt::transparent
);
348 QPainter
p(&pixmap1
);
349 p
.setOpacity(1.0 - hoverOpacity());
350 p
.drawPixmap(0, 0, m_pixmap
);
353 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
354 QPixmap
pixmap2(pixmap1
.size());
355 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
356 pixmap2
.fill(Qt::transparent
);
358 QPainter
p(&pixmap2
);
359 p
.setOpacity(hoverOpacity());
360 p
.drawPixmap(0, 0, m_hoverPixmap
);
363 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
364 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
365 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
367 QPainter
p(&pixmap1
);
368 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
369 p
.drawPixmap(0, 0, pixmap2
);
372 // Finally paint pixmap1 on the widget
373 drawPixmap(painter
, pixmap1
);
375 drawPixmap(painter
, m_hoverPixmap
);
377 } else if (!m_pixmap
.isNull()) {
378 drawPixmap(painter
, m_pixmap
);
381 painter
->setFont(m_customizedFont
);
382 painter
->setPen(textColor());
383 const TextInfo
* textInfo
= m_textInfo
.value("text");
386 // It seems that we can end up here even if m_textInfo does not contain
387 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
388 // this can only happen if the index is negative. This can happen when
389 // the item is about to be removed, see KItemListView::slotItemsRemoved().
390 // TODO: try to reproduce the crash and find a better fix.
394 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
396 bool clipAdditionalInfoBounds
= false;
397 if (m_supportsItemExpanding
) {
398 // Prevent a possible overlapping of the additional-information texts
399 // with the icon. This can happen if the user has minimized the width
400 // of the name-column to a very small value.
401 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
402 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
403 clipAdditionalInfoBounds
= true;
405 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
409 painter
->setPen(m_additionalInfoTextColor
);
410 painter
->setFont(m_customizedFont
);
412 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
413 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
414 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
417 if (!m_rating
.isNull()) {
418 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
419 QPointF pos
= ratingTextInfo
->pos
;
420 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
421 if (align
& Qt::AlignHCenter
) {
422 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
424 painter
->drawPixmap(pos
, m_rating
);
427 if (clipAdditionalInfoBounds
) {
431 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
432 painter
->setBrush(Qt::NoBrush
);
433 painter
->setPen(Qt::green
);
434 painter
->drawRect(m_iconRect
);
436 painter
->setPen(Qt::blue
);
437 painter
->drawRect(m_textRect
);
439 painter
->setPen(Qt::red
);
440 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
441 painter
->drawRect(rect());
445 QRectF
KStandardItemListWidget::iconRect() const
447 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
451 QRectF
KStandardItemListWidget::textRect() const
453 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
457 QRectF
KStandardItemListWidget::textFocusRect() const
459 // In the compact- and details-layout a larger textRect() is returned to be aligned
460 // with the iconRect(). This is useful to have a larger selection/hover-area
461 // when having a quite large icon size but only one line of text. Still the
462 // focus rectangle should be shown as narrow as possible around the text.
464 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
467 case CompactLayout
: {
468 QRectF rect
= m_textRect
;
469 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
470 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
471 rect
.setTop(topText
->pos
.y());
472 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
476 case DetailsLayout
: {
477 QRectF rect
= m_textRect
;
478 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
479 rect
.setTop(textInfo
->pos
.y());
480 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
482 const KItemListStyleOption
& option
= styleOption();
483 if (option
.extendedSelectionRegion
) {
484 const QString text
= textInfo
->staticText
.text();
485 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
498 QRectF
KStandardItemListWidget::selectionRect() const
500 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
507 case DetailsLayout
: {
508 const int padding
= styleOption().padding
;
509 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
510 QRectF result
= adjustedIconRect
| m_textRect
;
511 if (m_highlightEntireRow
) {
512 result
.setRight(m_columnWidthSum
+ leadingPadding());
525 QRectF
KStandardItemListWidget::expansionToggleRect() const
527 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
528 return m_isExpandable
? m_expansionArea
: QRectF();
531 QRectF
KStandardItemListWidget::selectionToggleRect() const
533 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
535 const int widgetIconSize
= iconSize();
536 int toggleSize
= KIconLoader::SizeSmall
;
537 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
538 toggleSize
= KIconLoader::SizeMedium
;
539 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
540 toggleSize
= KIconLoader::SizeSmallMedium
;
543 QPointF pos
= iconRect().topLeft();
545 // If the selection toggle has a very small distance to the
546 // widget borders, the size of the selection toggle will get
547 // increased to prevent an accidental clicking of the item
548 // when trying to hit the toggle.
549 const int widgetHeight
= size().height();
550 const int widgetWidth
= size().width();
551 const int minMargin
= 2;
553 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
554 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
555 toggleSize
= widgetHeight
;
558 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
559 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
560 toggleSize
= widgetWidth
;
564 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
567 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
570 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
571 if (m_layout
!= DetailsLayout
) {
575 // Only return the content of the text-column as pixmap
576 const int leftClip
= m_pixmapPos
.x();
578 const TextInfo
* textInfo
= m_textInfo
.value("text");
579 const int rightClip
= textInfo
->pos
.x() +
580 textInfo
->staticText
.size().width() +
581 2 * styleOption().padding
;
583 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
584 clippedPixmap
.fill(Qt::transparent
);
586 QPainter
painter(&clippedPixmap
);
587 painter
.drawPixmap(-leftClip
, 0, pixmap
);
589 return clippedPixmap
;
593 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
595 return new KStandardItemListWidgetInformant();
598 void KStandardItemListWidget::invalidateCache()
600 m_dirtyLayout
= true;
601 m_dirtyContent
= true;
604 void KStandardItemListWidget::invalidateIconCache()
606 m_dirtyContent
= true;
607 m_dirtyContentRoles
.insert("iconPixmap");
608 m_dirtyContentRoles
.insert("iconOverlays");
611 void KStandardItemListWidget::refreshCache()
615 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
621 bool KStandardItemListWidget::isHidden() const
626 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
631 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
633 return QPalette::Text
;
636 void KStandardItemListWidget::setTextColor(const QColor
& color
)
638 if (color
!= m_customTextColor
) {
639 m_customTextColor
= color
;
640 updateAdditionalInfoTextColor();
645 QColor
KStandardItemListWidget::textColor() const
649 return m_additionalInfoTextColor
;
650 } else if (m_customTextColor
.isValid()) {
651 return m_customTextColor
;
655 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
656 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
657 return styleOption().palette
.color(group
, role
);
660 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
663 m_dirtyContent
= true;
667 QPixmap
KStandardItemListWidget::overlay() const
673 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
674 const QHash
<QByteArray
, QVariant
>& values
) const
676 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
679 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
680 const QSet
<QByteArray
>& roles
)
684 m_dirtyContent
= true;
686 QSet
<QByteArray
> dirtyRoles
;
687 if (roles
.isEmpty()) {
688 const auto visibleRoles
= this->visibleRoles();
689 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
694 // The URL might have changed (i.e., if the sort order of the items has
695 // been changed). Therefore, the "is cut" state must be updated.
696 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
697 const QUrl itemUrl
= data().value("url").toUrl();
698 m_isCut
= clipboard
->isCut(itemUrl
);
700 // The icon-state might depend from other roles and hence is
701 // marked as dirty whenever a role has been changed
702 dirtyRoles
.insert("iconPixmap");
703 dirtyRoles
.insert("iconName");
705 QSetIterator
<QByteArray
> it(dirtyRoles
);
706 while (it
.hasNext()) {
707 const QByteArray
& role
= it
.next();
708 m_dirtyContentRoles
.insert(role
);
712 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
713 const QList
<QByteArray
>& previous
)
716 m_sortedVisibleRoles
= current
;
717 m_dirtyLayout
= true;
720 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
727 m_dirtyLayout
= true;
730 void KStandardItemListWidget::leadingPaddingChanged(qreal padding
) {
732 m_dirtyLayout
= true;
735 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
736 const KItemListStyleOption
& previous
)
738 KItemListWidget::styleOptionChanged(current
, previous
);
740 updateAdditionalInfoTextColor();
741 m_dirtyLayout
= true;
744 void KStandardItemListWidget::hoveredChanged(bool hovered
)
747 m_dirtyLayout
= true;
750 void KStandardItemListWidget::selectedChanged(bool selected
)
753 updateAdditionalInfoTextColor();
754 m_dirtyContent
= true;
757 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
761 m_dirtyLayout
= true;
764 int KStandardItemListWidget::selectionLength(const QString
& text
) const
766 return text
.length();
769 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
773 QGraphicsView
* parent
= scene()->views()[0];
774 if (current
.isEmpty() || !parent
|| current
!= "text") {
776 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
778 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
779 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
780 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
781 this, &KStandardItemListWidget::slotRoleEditingFinished
);
783 if (m_oldRoleEditor
) {
784 m_oldRoleEditor
->deleteLater();
786 m_oldRoleEditor
= m_roleEditor
;
787 m_roleEditor
->hide();
788 m_roleEditor
= nullptr;
793 Q_ASSERT(!m_roleEditor
);
795 const TextInfo
* textInfo
= m_textInfo
.value("text");
797 m_roleEditor
= new KItemListRoleEditor(parent
);
798 m_roleEditor
->setRole(current
);
799 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
800 m_roleEditor
->setFont(styleOption().font
);
802 const QString text
= data().value(current
).toString();
803 m_roleEditor
->setPlainText(text
);
805 QTextOption textOption
= textInfo
->staticText
.textOption();
806 m_roleEditor
->document()->setDefaultTextOption(textOption
);
808 const int textSelectionLength
= selectionLength(text
);
810 if (textSelectionLength
> 0) {
811 QTextCursor cursor
= m_roleEditor
->textCursor();
812 cursor
.movePosition(QTextCursor::StartOfBlock
);
813 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
814 m_roleEditor
->setTextCursor(cursor
);
817 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
818 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
819 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
820 this, &KStandardItemListWidget::slotRoleEditingFinished
);
822 // Adjust the geometry of the editor
823 QRectF rect
= roleEditingRect(current
);
824 const int frameWidth
= m_roleEditor
->frameWidth();
825 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
826 rect
.translate(pos());
827 if (rect
.right() > parent
->width()) {
828 rect
.setWidth(parent
->width() - rect
.left());
830 m_roleEditor
->setGeometry(rect
.toRect());
831 m_roleEditor
->show();
832 m_roleEditor
->setFocus();
835 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
837 KItemListWidget::iconSizeChanged(current
, previous
);
839 invalidateIconCache();
840 triggerCacheRefreshing();
844 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
847 setEditedRole(QByteArray());
848 Q_ASSERT(!m_roleEditor
);
851 KItemListWidget::resizeEvent(event
);
853 m_dirtyLayout
= true;
856 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
858 KItemListWidget::showEvent(event
);
860 // Listen to changes of the clipboard to mark the item as cut/uncut
861 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
863 const QUrl itemUrl
= data().value("url").toUrl();
864 m_isCut
= clipboard
->isCut(itemUrl
);
866 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
867 this, &KStandardItemListWidget::slotCutItemsChanged
);
870 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
872 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
873 this, &KStandardItemListWidget::slotCutItemsChanged
);
875 KItemListWidget::hideEvent(event
);
878 bool KStandardItemListWidget::event(QEvent
*event
)
880 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
881 || event
->type() == QEvent::PaletteChange
) {
882 m_dirtyContent
= true;
885 return KItemListWidget::event(event
);
888 void KStandardItemListWidget::finishRoleEditing()
890 if (!editedRole().isEmpty() && m_roleEditor
) {
891 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
895 void KStandardItemListWidget::slotCutItemsChanged()
897 const QUrl itemUrl
= data().value("url").toUrl();
898 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
899 if (m_isCut
!= isCut
) {
901 m_pixmap
= QPixmap();
902 m_dirtyContent
= true;
907 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
908 const QVariant
& value
)
911 Q_EMIT
roleEditingCanceled(index(), role
, value
);
912 setEditedRole(QByteArray());
915 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
916 const QVariant
& value
)
919 Q_EMIT
roleEditingFinished(index(), role
, value
);
920 setEditedRole(QByteArray());
923 void KStandardItemListWidget::triggerCacheRefreshing()
925 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
931 const QHash
<QByteArray
, QVariant
> values
= data();
932 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
933 m_isHidden
= isHidden();
934 m_customizedFont
= customizedFont(styleOption().font
);
935 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
936 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(),
937 qreal(), [this](qreal sum
, const auto &role
){ return sum
+ columnWidth(role
); });
939 updateExpansionArea();
944 m_dirtyLayout
= false;
945 m_dirtyContent
= false;
946 m_dirtyContentRoles
.clear();
949 void KStandardItemListWidget::updateExpansionArea()
951 if (m_supportsItemExpanding
) {
952 const QHash
<QByteArray
, QVariant
> values
= data();
953 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
954 if (expandedParentsCount
>= 0) {
955 const int widgetIconSize
= iconSize();
956 const qreal widgetHeight
= size().height();
957 const qreal inc
= (widgetHeight
- iconSize()) / 2;
959 layoutDirection() == Qt::LeftToRight
960 ? expandedParentsCount
* widgetHeight
+ inc
961 : size().width() - iconSize() - (expandedParentsCount
* widgetHeight
+ inc
);
963 const qreal xPadding
= m_highlightEntireRow
? leadingPadding() : 0;
964 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
969 m_expansionArea
= QRectF();
972 void KStandardItemListWidget::updatePixmapCache()
974 // Precondition: Requires already updated m_textPos values to calculate
975 // the remaining height when the alignment is vertical.
977 const QSizeF widgetSize
= size();
978 const bool iconOnTop
= (m_layout
== IconsLayout
);
979 const KItemListStyleOption
& option
= styleOption();
980 const qreal padding
= option
.padding
;
982 const int widgetIconSize
= iconSize();
983 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
984 const int maxIconHeight
= widgetIconSize
;
986 const QHash
<QByteArray
, QVariant
> values
= data();
988 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
989 if (!updatePixmap
&& m_dirtyContent
) {
990 updatePixmap
= m_dirtyContentRoles
.isEmpty()
991 || m_dirtyContentRoles
.contains("iconPixmap")
992 || m_dirtyContentRoles
.contains("iconName")
993 || m_dirtyContentRoles
.contains("iconOverlays");
997 m_pixmap
= QPixmap();
999 int sequenceIndex
= hoverSequenceIndex();
1001 if (values
.contains("hoverSequencePixmaps")) {
1002 // Use one of the hover sequence pixmaps instead of the default
1005 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1007 if (values
.contains("hoverSequenceWraparoundPoint")) {
1008 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1010 sequenceIndex
%= static_cast<int>(wap
);
1014 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
1016 if (loadedIndex
!= 0) {
1017 m_pixmap
= pixmaps
[loadedIndex
];
1021 if (m_pixmap
.isNull()) {
1022 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1025 if (m_pixmap
.isNull()) {
1026 // Use the icon that fits to the MIME-type
1027 QString iconName
= values
["iconName"].toString();
1028 if (iconName
.isEmpty()) {
1029 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1030 // use a generic icon as fallback
1031 iconName
= QStringLiteral("unknown");
1033 const QStringList overlays
= values
["iconOverlays"].toStringList();
1034 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1036 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1037 // A custom pixmap has been applied. Assure that the pixmap
1038 // is scaled to the maximum available size.
1039 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1042 if (m_pixmap
.isNull()) {
1043 m_hoverPixmap
= QPixmap();
1048 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1049 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1053 KIconEffect::semiTransparent(m_pixmap
);
1056 if (m_layout
== IconsLayout
&& isSelected()) {
1057 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1058 QImage image
= m_pixmap
.toImage();
1059 if (image
.isNull()) {
1060 m_hoverPixmap
= QPixmap();
1063 KIconEffect::colorize(image
, color
, 0.8f
);
1064 m_pixmap
= QPixmap::fromImage(image
);
1068 if (!m_overlay
.isNull()) {
1069 QPainter
painter(&m_pixmap
);
1070 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1073 int scaledIconSize
= 0;
1075 const TextInfo
* textInfo
= m_textInfo
.value("text");
1076 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1078 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1079 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1080 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1081 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1084 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1085 const int maxScaledIconHeight
= scaledIconSize
;
1087 m_scaledPixmapSize
= m_pixmap
.size();
1088 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1089 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1092 // Center horizontally and align on bottom within the icon-area
1093 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1094 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1096 // Center horizontally and vertically within the icon-area
1097 const TextInfo
* textInfo
= m_textInfo
.value("text");
1098 const auto width
= (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0;
1099 const auto iPadding
= 2.0 * padding
;
1100 const auto x
= textInfo
->pos
.x();
1102 const QHash
<QByteArray
, QVariant
> values
= data();
1103 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1104 const int expansionOffset
=
1105 (m_layout
== DetailsLayout
) ?
1106 size().height() + size().height() * expandedParentsCount
:
1109 m_pixmapPos
.setX(layoutDirection() == Qt::LeftToRight
1110 ? x
- iPadding
- width
1111 : size().width() - iPadding
- width
- expansionOffset
);
1113 // Derive icon's vertical center from the center of the text frame, including
1114 // any necessary adjustment if the font's midline is offset from the frame center
1115 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1116 - m_customizedFontMetrics
.descent()
1117 - m_customizedFontMetrics
.capHeight() / 2.0;
1118 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1122 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1124 // Prepare the pixmap that is used when the item gets hovered
1126 m_hoverPixmap
= m_pixmap
;
1127 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1128 // In the KIconLoader terminology, active = hover.
1129 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1130 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1132 m_hoverPixmap
= m_pixmap
;
1134 } else if (hoverOpacity() <= 0.0) {
1135 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1136 m_hoverPixmap
= QPixmap();
1140 void KStandardItemListWidget::updateTextsCache()
1142 QTextOption textOption
;
1145 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1146 textOption
.setAlignment(Qt::AlignHCenter
);
1150 textOption
.setAlignment(Qt::AlignLeft
);
1151 textOption
.setWrapMode(QTextOption::NoWrap
);
1158 qDeleteAll(m_textInfo
);
1160 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1161 TextInfo
* textInfo
= new TextInfo();
1162 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1163 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1164 textInfo
->staticText
.setTextOption(textOption
);
1165 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1169 case IconsLayout
: updateIconsLayoutTextCache(); break;
1170 case CompactLayout
: updateCompactLayoutTextCache(); break;
1171 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1172 default: Q_ASSERT(false); break;
1175 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1176 if (ratingTextInfo
) {
1177 // The text of the rating-role has been set to empty to get
1178 // replaced by a rating-image showing the rating as stars.
1179 const KItemListStyleOption
& option
= styleOption();
1180 QSizeF ratingSize
= preferredRatingSize(option
);
1182 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1183 ? columnWidth("rating") - columnPadding(option
)
1185 if (ratingSize
.width() > availableWidth
) {
1186 ratingSize
.rwidth() = availableWidth
;
1188 const qreal dpr
= qApp
->devicePixelRatio();
1189 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1190 m_rating
.setDevicePixelRatio(dpr
);
1191 m_rating
.fill(Qt::transparent
);
1193 QPainter
painter(&m_rating
);
1194 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1195 const int rating
= data().value("rating").toInt();
1196 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1197 } else if (!m_rating
.isNull()) {
1198 m_rating
= QPixmap();
1202 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1204 const auto extensionIndex
= text
.lastIndexOf('.');
1205 if (extensionIndex
!= -1) {
1206 // has file extension
1207 const auto extensionLength
= text
.length() - extensionIndex
;
1208 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1209 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1210 // if we have room to display the file extension and the extension is not too long
1211 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1213 elidingWidth
- extensionWidth
);
1214 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1215 ret
.append(text
.rightRef(extensionLength
));
1217 ret
.append(QStringView(text
).right(extensionLength
));
1222 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1226 void KStandardItemListWidget::updateIconsLayoutTextCache()
1233 // might get wrapped above
1235 // Additional role 1
1236 // Additional role 2
1238 const QHash
<QByteArray
, QVariant
> values
= data();
1240 const KItemListStyleOption
& option
= styleOption();
1241 const qreal padding
= option
.padding
;
1242 const qreal maxWidth
= size().width() - 2 * padding
;
1243 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1245 // Initialize properties for the "text" role. It will be used as anchor
1246 // for initializing the position of the other roles.
1247 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1248 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1249 nameTextInfo
->staticText
.setText(nameText
);
1251 // Calculate the number of lines required for the name and the required width
1252 qreal nameWidth
= 0;
1253 qreal nameHeight
= 0;
1256 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1257 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1258 layout
.beginLayout();
1259 int nameLineIndex
= 0;
1260 while ((line
= layout
.createLine()).isValid()) {
1261 line
.setLineWidth(maxWidth
);
1262 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1263 nameHeight
+= line
.height();
1266 if (nameLineIndex
== option
.maxTextLines
) {
1267 // The maximum number of textlines has been reached. If this is
1268 // the case provide an elided text if necessary.
1269 const int textLength
= line
.textStart() + line
.textLength();
1270 if (textLength
< nameText
.length()) {
1271 // Elide the last line of the text
1272 qreal elidingWidth
= maxWidth
;
1273 qreal lastLineWidth
;
1275 QString lastTextLine
= nameText
.mid(line
.textStart());
1276 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1277 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1278 nameTextInfo
->staticText
.setText(elidedText
);
1280 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1282 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1283 // to avoid problems related to different width calculation code paths
1284 // within Qt. (see bug 337104)
1285 elidingWidth
-= 1.0;
1286 } while (lastLineWidth
> maxWidth
);
1288 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1295 // Use one line for each additional information
1296 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1297 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1298 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1299 nameTextInfo
->pos
.y(),
1303 // Calculate the position for each additional information
1304 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1305 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1306 if (role
== "text") {
1310 const QString text
= roleText(role
, values
);
1311 TextInfo
* textInfo
= m_textInfo
.value(role
);
1312 textInfo
->staticText
.setText(text
);
1314 qreal requiredWidth
= 0;
1316 QTextLayout
layout(text
, m_customizedFont
);
1317 QTextOption textOption
;
1318 textOption
.setWrapMode(QTextOption::NoWrap
);
1319 layout
.setTextOption(textOption
);
1321 layout
.beginLayout();
1322 QTextLine textLine
= layout
.createLine();
1323 if (textLine
.isValid()) {
1324 textLine
.setLineWidth(maxWidth
);
1325 requiredWidth
= textLine
.naturalTextWidth();
1326 if (requiredWidth
> maxWidth
) {
1327 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1328 textInfo
->staticText
.setText(elidedText
);
1329 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1330 } else if (role
== "rating") {
1331 // Use the width of the rating pixmap, because the rating text is empty.
1332 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1337 textInfo
->pos
= QPointF(padding
, y
);
1338 textInfo
->staticText
.setTextWidth(maxWidth
);
1340 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1342 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1343 if (!textRect
.isEmpty()) {
1344 m_textRect
|= textRect
;
1350 // Add a padding to the text rectangle
1351 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1354 void KStandardItemListWidget::updateCompactLayoutTextCache()
1356 // +------+ Name role
1357 // | Icon | Additional role 1
1358 // +------+ Additional role 2
1360 const QHash
<QByteArray
, QVariant
> values
= data();
1362 const KItemListStyleOption
& option
= styleOption();
1363 const qreal widgetHeight
= size().height();
1364 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1365 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1367 qreal maximumRequiredTextWidth
= 0;
1368 const qreal x
= option
.padding
* 3 + iconSize();
1369 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1370 const qreal maxWidth
= size().width() - x
- option
.padding
;
1371 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1372 const QString text
= roleText(role
, values
);
1373 TextInfo
* textInfo
= m_textInfo
.value(role
);
1374 textInfo
->staticText
.setText(text
);
1376 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1377 if (requiredWidth
> maxWidth
) {
1378 requiredWidth
= maxWidth
;
1379 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1380 textInfo
->staticText
.setText(elidedText
);
1383 if (layoutDirection() == Qt::LeftToRight
) {
1384 textInfo
->pos
= QPointF(x
, y
);
1386 textInfo
->pos
= QPointF(x
- size().height(), y
);
1388 textInfo
->staticText
.setTextWidth(maxWidth
);
1390 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1395 if (layoutDirection() == Qt::LeftToRight
) {
1396 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1398 m_textRect
= QRectF(x
- option
.padding
- size().height(), 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1402 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1404 // Precondition: Requires already updated m_expansionArea
1405 // to determine the left position.
1408 // | Icon | Name role Additional role 1 Additional role 2
1410 m_textRect
= QRectF();
1412 const KItemListStyleOption
& option
= styleOption();
1413 const QHash
<QByteArray
, QVariant
> values
= data();
1415 const qreal widgetHeight
= size().height();
1416 const int fontHeight
= m_customizedFontMetrics
.height();
1418 const qreal columnWidthInc
= columnPadding(option
);
1420 qreal firstColumnOffset
= iconSize();
1421 if (m_supportsItemExpanding
) {
1422 firstColumnOffset
+= (m_expansionArea
.width() + widgetHeight
) / 2;
1424 firstColumnOffset
+= option
.padding
+ leadingPadding();
1427 qreal x
= firstColumnOffset
;
1428 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1430 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1431 QString text
= roleText(role
, values
);
1433 // Elide the text in case it does not fit into the available column-width
1434 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1435 const qreal roleWidth
= columnWidth(role
);
1436 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1438 const QHash
<QByteArray
, QVariant
> values
= data();
1439 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1440 const int expansionOffset
= size().height() * expandedParentsCount
;
1442 const bool isTextRole
= (role
== "text");
1444 availableTextWidth
-= firstColumnOffset
- leadingPadding();
1447 if (requiredWidth
> availableTextWidth
) {
1448 text
= elideRightKeepExtension(text
, availableTextWidth
);
1449 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1452 TextInfo
* textInfo
= m_textInfo
.value(role
);
1453 textInfo
->staticText
.setText(text
);
1454 textInfo
->pos
= QPointF(x
- (layoutDirection() == Qt::LeftToRight
? 0 : firstColumnOffset
), y
);
1455 if (layoutDirection() == Qt::LeftToRight
) {
1456 textInfo
->pos
.rx() += columnWidthInc
/2 + expansionOffset
;
1458 textInfo
->pos
.rx() -= expansionOffset
;
1459 if (textInfo
->pos
.x() < iconSize()) {
1460 textInfo
->pos
.rx() = iconSize();
1466 const qreal textWidth
= option
.extendedSelectionRegion
1467 ? size().width() - textInfo
->pos
.x()
1468 : requiredWidth
+ 2 * option
.padding
;
1469 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1470 textWidth
, size().height());
1472 // The column after the name should always be aligned on the same x-position independent
1473 // from the expansion-level shown in the name column
1474 x
-= firstColumnOffset
- leadingPadding();
1475 } else if (isRoleRightAligned(role
)) {
1476 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1481 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1484 if (m_customTextColor
.isValid()) {
1485 c1
= m_customTextColor
;
1486 } else if (isSelected()) {
1487 // The detail text colour needs to match the main text (HighlightedText) for the same level
1488 // of readability. We short circuit early here to avoid interpolating with another colour.
1489 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1492 c1
= styleOption().palette
.text().color();
1495 // For the color of the additional info the inactive text color
1496 // is not used as this might lead to unreadable text for some color schemes. Instead
1497 // the text color c1 is slightly mixed with the background color.
1498 const QColor c2
= styleOption().palette
.base().color();
1500 const int p2
= 100 - p1
;
1501 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1502 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1503 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1506 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1508 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1509 QPixmap scaledPixmap
= pixmap
;
1510 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1511 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1512 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1514 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1515 painter
->setPen(Qt::blue
);
1516 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1519 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1523 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1525 const int siblingSize
= size().height();
1526 const int x
= (m_expansionArea
.width() - siblingSize
) / 2;
1528 const QHash
<QByteArray
, QVariant
> values
= data();
1529 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1530 const int expansionOffset
= siblingSize
* expandedParentsCount
;
1533 layoutDirection() == Qt::LeftToRight
1534 ? x
+ expansionOffset
1535 : size().width() - x
- siblingSize
- expansionOffset
, 0, siblingSize
, siblingSize
);
1537 bool isItemSibling
= true;
1539 const QBitArray siblings
= siblingsInformation();
1540 QStyleOption option
;
1541 option
.direction
= layoutDirection();
1542 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1543 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1544 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1545 option
.rect
= siblingRect
;
1546 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1547 if (isItemSibling
) {
1548 option
.state
|= QStyle::State_Item
;
1549 if (m_isExpandable
) {
1550 option
.state
|= QStyle::State_Children
;
1552 if (data().value("isExpanded").toBool()) {
1553 option
.state
|= QStyle::State_Open
;
1555 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1556 isItemSibling
= false;
1558 option
.palette
.setColor(QPalette::Text
, normalColor
);
1561 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1563 if (layoutDirection() == Qt::LeftToRight
) {
1564 siblingRect
.translate(-siblingRect
.width(), 0);
1566 siblingRect
.translate(siblingRect
.width(), 0);
1571 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1573 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1578 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1579 if (m_layout
== DetailsLayout
) {
1580 rect
.setWidth(columnWidth(role
) - rect
.x());
1586 void KStandardItemListWidget::closeRoleEditor()
1588 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1589 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1590 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1591 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1593 if (m_roleEditor
->hasFocus()) {
1594 // If the editing was not ended by a FocusOut event, we have
1595 // to transfer the keyboard focus back to the KItemListContainer.
1596 scene()->views()[0]->parentWidget()->setFocus();
1599 if (m_oldRoleEditor
) {
1600 m_oldRoleEditor
->deleteLater();
1602 m_oldRoleEditor
= m_roleEditor
;
1603 m_roleEditor
->hide();
1604 m_roleEditor
= nullptr;
1607 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1609 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1611 size
*= qApp
->devicePixelRatio();
1613 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1616 if (!QPixmapCache::find(key
, &pixmap
)) {
1617 QIcon icon
= QIcon::fromTheme(name
);
1618 if (icon
.isNull()) {
1622 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1623 icon
= fallbackIcon
;
1626 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1627 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1628 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1631 // Strangely KFileItem::overlays() returns empty string-values, so
1632 // we need to check first whether an overlay must be drawn at all.
1633 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1634 // assumes that an overlay will be drawn and has some additional
1636 for (const QString
& overlay
: overlays
) {
1637 if (!overlay
.isEmpty()) {
1638 int state
= KIconLoader::DefaultState
;
1644 state
= KIconLoader::ActiveState
;
1646 case QIcon::Disabled
:
1647 state
= KIconLoader::DisabledState
;
1649 case QIcon::Selected
:
1650 state
= KIconLoader::SelectedState
;
1654 // There is at least one overlay, draw all overlays above m_pixmap
1655 // and cancel the check
1656 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1661 QPixmapCache::insert(key
, pixmap
);
1663 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1668 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1670 const qreal height
= option
.fontMetrics
.ascent();
1671 return QSizeF(height
* 5, height
);
1674 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1676 return option
.padding
* 6;