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/kitemviewsutils.h"
14 #include "private/kpixmapmodifier.h"
16 #include <KIconEffect>
17 #include <KIconLoader>
18 #include <KRatingPainter>
19 #include <KStringHandler>
21 #include <QApplication>
22 #include <QGraphicsScene>
23 #include <QGraphicsSceneResizeEvent>
24 #include <QGraphicsView>
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
,
40 qreal
&logicalWidthHint
,
41 const KItemListView
*view
) const
43 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
44 case KStandardItemListView::IconsLayout
:
45 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
48 case KStandardItemListView::CompactLayout
:
49 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
52 case KStandardItemListView::DetailsLayout
:
53 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
62 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, 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
, const QHash
<QByteArray
, QVariant
> &values
) const
111 if (role
== "rating") {
112 // Always use an empty text, as the rating is shown by the image m_rating.
115 return values
.value(role
).toString();
118 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
123 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
124 qreal
&logicalWidthHint
,
125 const KItemListView
*view
) const
127 const KItemListStyleOption
&option
= view
->styleOption();
128 const QFont
&normalFont
= option
.font
;
129 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
131 const qreal itemWidth
= view
->itemSize().width();
132 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
133 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
134 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
136 const QFont linkFont
= customizedFontForLinks(normalFont
);
138 QTextOption
textOption(Qt::AlignHCenter
);
139 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
141 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
142 if (logicalHeightHints
.at(index
).first
> 0.0) {
146 // If the current item is a link, we use the customized link font instead of the normal font.
147 const QFont
&font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
149 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
151 // Calculate the number of lines required for wrapping the name
152 qreal textHeight
= 0;
153 QTextLayout
layout(text
, font
);
154 layout
.setTextOption(textOption
);
155 layout
.beginLayout();
158 bool isElided
= false;
159 while ((line
= layout
.createLine()).isValid()) {
160 line
.setLineWidth(maxWidth
);
161 line
.naturalTextWidth();
162 textHeight
+= line
.height();
165 if (lineCount
== option
.maxTextLines
) {
166 isElided
= layout
.createLine().isValid();
172 // Add one line for each additional information
173 textHeight
+= additionalRolesSpacing
;
175 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
176 logicalHeightHints
[index
].second
= isElided
;
179 logicalWidthHint
= itemWidth
;
182 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
183 qreal
&logicalWidthHint
,
184 const KItemListView
*view
) const
186 const KItemListStyleOption
&option
= view
->styleOption();
187 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
188 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
190 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
191 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
192 const qreal maxWidth
= option
.maxTextWidth
;
193 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
194 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
196 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
198 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
199 if (logicalHeightHints
.at(index
).first
> 0.0) {
203 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
204 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
206 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
207 // to show all roles without horizontal clipping.
208 qreal maximumRequiredWidth
= 0.0;
210 if (showOnlyTextRole
) {
211 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
213 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
214 for (const QByteArray
&role
: visibleRoles
) {
215 const QString
&text
= roleText(role
, values
);
216 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
217 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
221 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
222 if (maxWidth
> 0 && width
> maxWidth
) {
226 logicalHeightHints
[index
].first
= width
;
229 logicalWidthHint
= height
;
232 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
233 qreal
&logicalWidthHint
,
234 const KItemListView
*view
) const
236 const KItemListStyleOption
&option
= view
->styleOption();
237 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
238 logicalHeightHints
.fill(std::make_pair(height
, false));
239 logicalWidthHint
= -1.0;
242 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
243 : KItemListWidget(informant
, parent
)
248 , m_customizedFontMetrics(m_customizedFont
)
249 , m_isExpandable(false)
250 , m_highlightEntireRow(false)
251 , m_supportsItemExpanding(false)
252 , m_dirtyLayout(true)
253 , m_dirtyContent(true)
254 , m_dirtyContentRoles()
255 , m_layout(IconsLayout
)
258 , m_scaledPixmapSize()
263 , m_sortedVisibleRoles()
265 , m_customTextColor()
266 , m_additionalInfoTextColor()
269 , m_roleEditor(nullptr)
270 , m_oldRoleEditor(nullptr)
274 KStandardItemListWidget::~KStandardItemListWidget()
276 qDeleteAll(m_textInfo
);
280 m_roleEditor
->deleteLater();
283 if (m_oldRoleEditor
) {
284 m_oldRoleEditor
->deleteLater();
288 void KStandardItemListWidget::setLayout(Layout layout
)
290 if (m_layout
!= layout
) {
292 m_dirtyLayout
= true;
293 updateAdditionalInfoTextColor();
298 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
300 if (m_highlightEntireRow
!= highlightEntireRow
) {
301 m_highlightEntireRow
= highlightEntireRow
;
302 m_dirtyLayout
= true;
307 bool KStandardItemListWidget::highlightEntireRow() const
309 return m_highlightEntireRow
;
312 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
314 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
315 m_supportsItemExpanding
= supportsItemExpanding
;
316 m_dirtyLayout
= true;
321 bool KStandardItemListWidget::supportsItemExpanding() const
323 return m_supportsItemExpanding
;
326 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
328 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
330 KItemListWidget::paint(painter
, option
, widget
);
332 if (!m_expansionArea
.isEmpty()) {
333 drawSiblingsInformation(painter
);
336 const KItemListStyleOption
&itemListStyleOption
= styleOption();
337 if (isHovered() && !m_pixmap
.isNull()) {
338 if (hoverOpacity() < 1.0) {
340 * Linear interpolation between m_pixmap and m_hoverPixmap.
342 * Note that this cannot be achieved by painting m_hoverPixmap over
343 * m_pixmap, even if the opacities are adjusted. For details see
344 * https://git.reviewboard.kde.org/r/109614/
346 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
347 QPixmap
pixmap1(m_pixmap
.size());
348 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
349 pixmap1
.fill(Qt::transparent
);
351 QPainter
p(&pixmap1
);
352 p
.setOpacity(1.0 - hoverOpacity());
353 p
.drawPixmap(0, 0, m_pixmap
);
356 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
357 QPixmap
pixmap2(pixmap1
.size());
358 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
359 pixmap2
.fill(Qt::transparent
);
361 QPainter
p(&pixmap2
);
362 p
.setOpacity(hoverOpacity());
363 p
.drawPixmap(0, 0, m_hoverPixmap
);
366 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
367 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
368 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
370 QPainter
p(&pixmap1
);
371 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
372 p
.drawPixmap(0, 0, pixmap2
);
375 // Finally paint pixmap1 on the widget
376 drawPixmap(painter
, pixmap1
);
378 drawPixmap(painter
, m_hoverPixmap
);
380 } else if (!m_pixmap
.isNull()) {
381 drawPixmap(painter
, m_pixmap
);
384 painter
->setFont(m_customizedFont
);
385 painter
->setPen(textColor(*widget
));
386 const TextInfo
*textInfo
= m_textInfo
.value("text");
389 // It seems that we can end up here even if m_textInfo does not contain
390 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
391 // this can only happen if the index is negative. This can happen when
392 // the item is about to be removed, see KItemListView::slotItemsRemoved().
393 // TODO: try to reproduce the crash and find a better fix.
397 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
399 bool clipAdditionalInfoBounds
= false;
400 if (m_supportsItemExpanding
) {
401 // Prevent a possible overlapping of the additional-information texts
402 // with the icon. This can happen if the user has minimized the width
403 // of the name-column to a very small value.
404 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
405 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
406 clipAdditionalInfoBounds
= true;
408 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
412 painter
->setPen(m_additionalInfoTextColor
);
413 painter
->setFont(m_customizedFont
);
415 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
416 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
417 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
420 if (!m_rating
.isNull()) {
421 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
422 QPointF pos
= ratingTextInfo
->pos
;
423 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
424 if (align
& Qt::AlignHCenter
) {
425 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
427 painter
->drawPixmap(pos
, m_rating
);
430 if (clipAdditionalInfoBounds
) {
434 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
435 painter
->setBrush(Qt::NoBrush
);
436 painter
->setPen(Qt::green
);
437 painter
->drawRect(m_iconRect
);
439 painter
->setPen(Qt::blue
);
440 painter
->drawRect(m_textRect
);
442 painter
->setPen(Qt::red
);
443 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
444 painter
->drawRect(rect());
448 QRectF
KStandardItemListWidget::iconRect() const
450 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
454 QRectF
KStandardItemListWidget::textRect() const
456 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
460 QRectF
KStandardItemListWidget::textFocusRect() const
462 // In the compact- and details-layout a larger textRect() is returned to be aligned
463 // with the iconRect(). This is useful to have a larger selection/hover-area
464 // when having a quite large icon size but only one line of text. Still the
465 // focus rectangle should be shown as narrow as possible around the text.
467 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
470 case CompactLayout
: {
471 QRectF rect
= m_textRect
;
472 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
473 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
474 rect
.setTop(topText
->pos
.y());
475 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
479 case DetailsLayout
: {
480 QRectF rect
= m_textRect
;
481 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
482 rect
.setTop(textInfo
->pos
.y());
483 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
485 const KItemListStyleOption
&option
= styleOption();
486 if (option
.extendedSelectionRegion
) {
487 const QString text
= textInfo
->staticText
.text();
488 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
501 QRectF
KStandardItemListWidget::selectionRect() const
503 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
510 case DetailsLayout
: {
511 const int padding
= styleOption().padding
;
512 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
513 QRectF result
= adjustedIconRect
| m_textRect
;
514 if (m_highlightEntireRow
) {
515 result
.setRight(m_columnWidthSum
+ sidePadding());
528 QRectF
KStandardItemListWidget::expansionToggleRect() const
530 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
531 return m_isExpandable
? m_expansionArea
: QRectF();
534 QRectF
KStandardItemListWidget::selectionToggleRect() const
536 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
538 const int widgetIconSize
= iconSize();
539 int toggleSize
= KIconLoader::SizeSmall
;
540 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
541 toggleSize
= KIconLoader::SizeMedium
;
542 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
543 toggleSize
= KIconLoader::SizeSmallMedium
;
546 QPointF pos
= iconRect().topLeft();
548 // If the selection toggle has a very small distance to the
549 // widget borders, the size of the selection toggle will get
550 // increased to prevent an accidental clicking of the item
551 // when trying to hit the toggle.
552 const int widgetHeight
= size().height();
553 const int widgetWidth
= size().width();
554 const int minMargin
= 2;
556 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
557 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
558 toggleSize
= widgetHeight
;
561 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
562 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
563 toggleSize
= widgetWidth
;
567 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
570 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
572 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
573 if (m_layout
!= DetailsLayout
) {
577 // Only return the content of the text-column as pixmap
578 const int leftClip
= m_pixmapPos
.x();
580 const TextInfo
*textInfo
= m_textInfo
.value("text");
581 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 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
;
592 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
594 return new KStandardItemListWidgetInformant();
597 void KStandardItemListWidget::invalidateCache()
599 m_dirtyLayout
= true;
600 m_dirtyContent
= true;
603 void KStandardItemListWidget::invalidateIconCache()
605 m_dirtyContent
= true;
606 m_dirtyContentRoles
.insert("iconPixmap");
607 m_dirtyContentRoles
.insert("iconOverlays");
610 void KStandardItemListWidget::refreshCache()
614 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
620 bool KStandardItemListWidget::isHidden() const
625 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
630 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
632 return QPalette::Text
;
635 void KStandardItemListWidget::setTextColor(const QColor
&color
)
637 if (color
!= m_customTextColor
) {
638 m_customTextColor
= color
;
639 updateAdditionalInfoTextColor();
644 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
648 return m_additionalInfoTextColor
;
649 } else if (m_customTextColor
.isValid()) {
650 return m_customTextColor
;
654 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
655 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
656 return styleOption().palette
.color(group
, role
);
659 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
662 m_dirtyContent
= true;
666 QPixmap
KStandardItemListWidget::overlay() const
671 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
673 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
676 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
680 m_dirtyContent
= true;
682 QSet
<QByteArray
> dirtyRoles
;
683 if (roles
.isEmpty()) {
684 const auto visibleRoles
= this->visibleRoles();
685 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
690 // The URL might have changed (i.e., if the sort order of the items has
691 // been changed). Therefore, the "is cut" state must be updated.
692 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
693 const QUrl itemUrl
= data().value("url").toUrl();
694 m_isCut
= clipboard
->isCut(itemUrl
);
696 // The icon-state might depend from other roles and hence is
697 // marked as dirty whenever a role has been changed
698 dirtyRoles
.insert("iconPixmap");
699 dirtyRoles
.insert("iconName");
701 QSetIterator
<QByteArray
> it(dirtyRoles
);
702 while (it
.hasNext()) {
703 const QByteArray
&role
= it
.next();
704 m_dirtyContentRoles
.insert(role
);
708 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
711 m_sortedVisibleRoles
= current
;
712 m_dirtyLayout
= true;
715 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
720 m_dirtyLayout
= true;
723 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
726 m_dirtyLayout
= true;
729 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
731 KItemListWidget::styleOptionChanged(current
, previous
);
733 updateAdditionalInfoTextColor();
734 m_dirtyLayout
= true;
737 void KStandardItemListWidget::hoveredChanged(bool hovered
)
740 m_dirtyLayout
= true;
743 void KStandardItemListWidget::selectedChanged(bool selected
)
746 updateAdditionalInfoTextColor();
747 m_dirtyContent
= true;
750 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
754 m_dirtyLayout
= true;
757 int KStandardItemListWidget::selectionLength(const QString
&text
) const
759 return text
.length();
762 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
766 QGraphicsView
*parent
= scene()->views()[0];
767 if (current
.isEmpty() || !parent
|| current
!= "text") {
769 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
771 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
772 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
774 if (m_oldRoleEditor
) {
775 m_oldRoleEditor
->deleteLater();
777 m_oldRoleEditor
= m_roleEditor
;
778 m_roleEditor
->hide();
779 m_roleEditor
= nullptr;
784 Q_ASSERT(!m_roleEditor
);
786 const TextInfo
*textInfo
= m_textInfo
.value("text");
788 m_roleEditor
= new KItemListRoleEditor(parent
);
789 m_roleEditor
->setRole(current
);
790 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
791 m_roleEditor
->setFont(styleOption().font
);
793 const QString text
= data().value(current
).toString();
794 m_roleEditor
->setPlainText(text
);
796 QTextOption textOption
= textInfo
->staticText
.textOption();
797 m_roleEditor
->document()->setDefaultTextOption(textOption
);
799 const int textSelectionLength
= selectionLength(text
);
801 if (textSelectionLength
> 0) {
802 QTextCursor cursor
= m_roleEditor
->textCursor();
803 cursor
.movePosition(QTextCursor::StartOfBlock
);
804 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
805 m_roleEditor
->setTextCursor(cursor
);
808 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
809 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
811 // Adjust the geometry of the editor
812 QRectF rect
= roleEditingRect(current
);
813 const int frameWidth
= m_roleEditor
->frameWidth();
814 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
815 rect
.translate(pos());
816 if (rect
.right() > parent
->width()) {
817 rect
.setWidth(parent
->width() - rect
.left());
819 m_roleEditor
->setGeometry(rect
.toRect());
820 m_roleEditor
->autoAdjustSize();
821 m_roleEditor
->show();
822 m_roleEditor
->setFocus();
825 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
827 KItemListWidget::iconSizeChanged(current
, previous
);
829 invalidateIconCache();
830 triggerCacheRefreshing();
834 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
837 setEditedRole(QByteArray());
838 Q_ASSERT(!m_roleEditor
);
841 KItemListWidget::resizeEvent(event
);
843 m_dirtyLayout
= true;
846 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
848 KItemListWidget::showEvent(event
);
850 // Listen to changes of the clipboard to mark the item as cut/uncut
851 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
853 const QUrl itemUrl
= data().value("url").toUrl();
854 m_isCut
= clipboard
->isCut(itemUrl
);
856 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
859 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
861 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
863 KItemListWidget::hideEvent(event
);
866 bool KStandardItemListWidget::event(QEvent
*event
)
868 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
869 m_dirtyContent
= true;
872 return KItemListWidget::event(event
);
875 void KStandardItemListWidget::finishRoleEditing()
877 if (!editedRole().isEmpty() && m_roleEditor
) {
878 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
882 void KStandardItemListWidget::slotCutItemsChanged()
884 const QUrl itemUrl
= data().value("url").toUrl();
885 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
886 if (m_isCut
!= isCut
) {
888 m_pixmap
= QPixmap();
889 m_dirtyContent
= true;
894 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
897 Q_EMIT
roleEditingCanceled(index(), role
, value
);
898 setEditedRole(QByteArray());
901 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
904 Q_EMIT
roleEditingFinished(index(), role
, value
);
905 setEditedRole(QByteArray());
908 void KStandardItemListWidget::triggerCacheRefreshing()
910 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
916 const QHash
<QByteArray
, QVariant
> values
= data();
917 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
918 m_isHidden
= isHidden();
919 m_customizedFont
= customizedFont(styleOption().font
);
920 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
921 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
922 return sum
+ columnWidth(role
);
925 updateExpansionArea();
930 m_dirtyLayout
= false;
931 m_dirtyContent
= false;
932 m_dirtyContentRoles
.clear();
935 void KStandardItemListWidget::updateExpansionArea()
937 if (m_supportsItemExpanding
) {
938 const QHash
<QByteArray
, QVariant
> values
= data();
939 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
940 if (expandedParentsCount
>= 0) {
941 const int widgetIconSize
= iconSize();
942 const qreal widgetHeight
= size().height();
943 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
944 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
946 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
947 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
952 m_expansionArea
= QRectF();
955 void KStandardItemListWidget::updatePixmapCache()
957 // Precondition: Requires already updated m_textPos values to calculate
958 // the remaining height when the alignment is vertical.
960 const QSizeF widgetSize
= size();
961 const bool iconOnTop
= (m_layout
== IconsLayout
);
962 const KItemListStyleOption
&option
= styleOption();
963 const qreal padding
= option
.padding
;
964 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
966 const int widgetIconSize
= iconSize();
967 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
968 const int maxIconHeight
= widgetIconSize
;
970 const QHash
<QByteArray
, QVariant
> values
= data();
972 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
973 if (!updatePixmap
&& m_dirtyContent
) {
974 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
975 || m_dirtyContentRoles
.contains("iconOverlays");
979 m_pixmap
= QPixmap();
981 int sequenceIndex
= hoverSequenceIndex();
983 if (values
.contains("hoverSequencePixmaps")) {
984 // Use one of the hover sequence pixmaps instead of the default
987 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
989 if (values
.contains("hoverSequenceWraparoundPoint")) {
990 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
992 sequenceIndex
%= static_cast<int>(wap
);
996 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
998 if (loadedIndex
!= 0) {
999 m_pixmap
= pixmaps
[loadedIndex
];
1003 if (m_pixmap
.isNull()) {
1004 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1007 if (m_pixmap
.isNull()) {
1008 // Use the icon that fits to the MIME-type
1009 QString iconName
= values
["iconName"].toString();
1010 if (iconName
.isEmpty()) {
1011 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1012 // use a generic icon as fallback
1013 iconName
= QStringLiteral("unknown");
1015 const QStringList overlays
= values
["iconOverlays"].toStringList();
1016 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1017 m_pixmap
= pixmapForIcon(iconName
,
1020 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1022 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1023 // A custom pixmap has been applied. Assure that the pixmap
1024 // is scaled to the maximum available size.
1025 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1028 if (m_pixmap
.isNull()) {
1029 m_hoverPixmap
= QPixmap();
1034 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1035 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1039 KIconEffect::semiTransparent(m_pixmap
);
1042 if (m_layout
== IconsLayout
&& isSelected()) {
1043 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1044 QImage image
= m_pixmap
.toImage();
1045 if (image
.isNull()) {
1046 m_hoverPixmap
= QPixmap();
1049 KIconEffect::colorize(image
, color
, 0.8f
);
1050 m_pixmap
= QPixmap::fromImage(image
);
1054 if (!m_overlay
.isNull()) {
1055 QPainter
painter(&m_pixmap
);
1056 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1059 int scaledIconSize
= 0;
1061 const TextInfo
*textInfo
= m_textInfo
.value("text");
1062 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1064 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1065 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1066 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1069 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1070 const int maxScaledIconHeight
= scaledIconSize
;
1072 m_scaledPixmapSize
= m_pixmap
.size();
1073 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1074 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1077 // Center horizontally and align on bottom within the icon-area
1078 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1079 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1081 // Center horizontally and vertically within the icon-area
1082 const TextInfo
*textInfo
= m_textInfo
.value("text");
1083 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1085 // Derive icon's vertical center from the center of the text frame, including
1086 // any necessary adjustment if the font's midline is offset from the frame center
1087 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1088 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1091 if (m_layout
== IconsLayout
) {
1092 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1094 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1095 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1096 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1097 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1098 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1101 // Prepare the pixmap that is used when the item gets hovered
1103 m_hoverPixmap
= m_pixmap
;
1104 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1105 // In the KIconLoader terminology, active = hover.
1106 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1107 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1109 m_hoverPixmap
= m_pixmap
;
1111 } else if (hoverOpacity() <= 0.0) {
1112 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1113 m_hoverPixmap
= QPixmap();
1117 void KStandardItemListWidget::updateTextsCache()
1119 QTextOption textOption
;
1122 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1123 textOption
.setAlignment(Qt::AlignHCenter
);
1127 textOption
.setAlignment(Qt::AlignLeft
);
1128 textOption
.setWrapMode(QTextOption::NoWrap
);
1135 qDeleteAll(m_textInfo
);
1137 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1138 TextInfo
*textInfo
= new TextInfo();
1139 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1140 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1141 textInfo
->staticText
.setTextOption(textOption
);
1142 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1147 updateIconsLayoutTextCache();
1150 updateCompactLayoutTextCache();
1153 updateDetailsLayoutTextCache();
1160 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1161 if (ratingTextInfo
) {
1162 // The text of the rating-role has been set to empty to get
1163 // replaced by a rating-image showing the rating as stars.
1164 const KItemListStyleOption
&option
= styleOption();
1165 QSizeF ratingSize
= preferredRatingSize(option
);
1167 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1168 if (ratingSize
.width() > availableWidth
) {
1169 ratingSize
.rwidth() = availableWidth
;
1171 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1172 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1173 m_rating
.setDevicePixelRatio(dpr
);
1174 m_rating
.fill(Qt::transparent
);
1176 QPainter
painter(&m_rating
);
1177 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1178 const int rating
= data().value("rating").toInt();
1179 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1180 } else if (!m_rating
.isNull()) {
1181 m_rating
= QPixmap();
1185 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1187 const auto extensionIndex
= text
.lastIndexOf('.');
1188 if (extensionIndex
!= -1) {
1189 // has file extension
1190 const auto extensionLength
= text
.length() - extensionIndex
;
1191 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1192 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1193 // if we have room to display the file extension and the extension is not too long
1194 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1195 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1196 ret
.append(text
.rightRef(extensionLength
));
1198 ret
.append(QStringView(text
).right(extensionLength
));
1203 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1206 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1208 QString
escaped(text
);
1210 const QChar
returnSymbol(0x21b5);
1211 escaped
.replace('\n', returnSymbol
);
1216 void KStandardItemListWidget::updateIconsLayoutTextCache()
1223 // might get wrapped above
1225 // Additional role 1
1226 // Additional role 2
1228 const QHash
<QByteArray
, QVariant
> values
= data();
1230 const KItemListStyleOption
&option
= styleOption();
1231 const qreal padding
= option
.padding
;
1232 const qreal maxWidth
= size().width() - 2 * padding
;
1233 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1235 // Initialize properties for the "text" role. It will be used as anchor
1236 // for initializing the position of the other roles.
1237 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1238 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1239 nameTextInfo
->staticText
.setText(nameText
);
1241 // Calculate the number of lines required for the name and the required width
1242 qreal nameWidth
= 0;
1243 qreal nameHeight
= 0;
1246 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1247 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1248 layout
.beginLayout();
1249 int nameLineIndex
= 0;
1250 while ((line
= layout
.createLine()).isValid()) {
1251 line
.setLineWidth(maxWidth
);
1252 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1253 nameHeight
+= line
.height();
1256 if (nameLineIndex
== option
.maxTextLines
) {
1257 // The maximum number of textlines has been reached. If this is
1258 // the case provide an elided text if necessary.
1259 const int textLength
= line
.textStart() + line
.textLength();
1260 if (textLength
< nameText
.length()) {
1261 // Elide the last line of the text
1262 qreal elidingWidth
= maxWidth
;
1263 qreal lastLineWidth
;
1265 QString lastTextLine
= nameText
.mid(line
.textStart());
1266 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1267 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1268 nameTextInfo
->staticText
.setText(elidedText
);
1270 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1272 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1273 // to avoid problems related to different width calculation code paths
1274 // within Qt. (see bug 337104)
1275 elidingWidth
-= 1.0;
1276 } while (lastLineWidth
> maxWidth
);
1278 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1285 // Use one line for each additional information
1286 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1287 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1288 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1290 // Calculate the position for each additional information
1291 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1292 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1293 if (role
== "text") {
1297 const QString text
= roleText(role
, values
);
1298 TextInfo
*textInfo
= m_textInfo
.value(role
);
1299 textInfo
->staticText
.setText(text
);
1301 qreal requiredWidth
= 0;
1303 QTextLayout
layout(text
, m_customizedFont
);
1304 QTextOption textOption
;
1305 textOption
.setWrapMode(QTextOption::NoWrap
);
1306 layout
.setTextOption(textOption
);
1308 layout
.beginLayout();
1309 QTextLine textLine
= layout
.createLine();
1310 if (textLine
.isValid()) {
1311 textLine
.setLineWidth(maxWidth
);
1312 requiredWidth
= textLine
.naturalTextWidth();
1313 if (requiredWidth
> maxWidth
) {
1314 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1315 textInfo
->staticText
.setText(elidedText
);
1316 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1317 } else if (role
== "rating") {
1318 // Use the width of the rating pixmap, because the rating text is empty.
1319 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1324 textInfo
->pos
= QPointF(padding
, y
);
1325 textInfo
->staticText
.setTextWidth(maxWidth
);
1327 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1329 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1330 if (!textRect
.isEmpty()) {
1331 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
;
1354 qreal maximumRequiredTextWidth
= 0;
1355 const qreal x
= option
.padding
* 3 + iconSize();
1356 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1357 const qreal maxWidth
= size().width() - x
- option
.padding
;
1358 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1359 const QString text
= escapeString(roleText(role
, values
));
1360 TextInfo
*textInfo
= m_textInfo
.value(role
);
1361 textInfo
->staticText
.setText(text
);
1363 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1364 if (requiredWidth
> maxWidth
) {
1365 requiredWidth
= maxWidth
;
1366 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1367 textInfo
->staticText
.setText(elidedText
);
1370 textInfo
->pos
= QPointF(x
, y
);
1371 textInfo
->staticText
.setTextWidth(maxWidth
);
1373 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1378 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1381 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1383 // Precondition: Requires already updated m_expansionArea
1384 // to determine the left position.
1387 // | Icon | Name role Additional role 1 Additional role 2
1389 m_textRect
= QRectF();
1391 const KItemListStyleOption
&option
= styleOption();
1392 const QHash
<QByteArray
, QVariant
> values
= data();
1394 const qreal widgetHeight
= size().height();
1395 const int fontHeight
= m_customizedFontMetrics
.height();
1397 const qreal columnWidthInc
= columnPadding(option
);
1398 qreal firstColumnInc
= iconSize();
1399 if (m_supportsItemExpanding
) {
1400 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1402 firstColumnInc
+= option
.padding
+ sidePadding();
1405 qreal x
= firstColumnInc
;
1406 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1408 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1409 QString text
= roleText(role
, values
);
1411 // Elide the text in case it does not fit into the available column-width
1412 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1413 const qreal roleWidth
= columnWidth(role
);
1414 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1416 const bool isTextRole
= (role
== "text");
1418 text
= escapeString(text
);
1419 availableTextWidth
-= firstColumnInc
- sidePadding();
1422 if (requiredWidth
> availableTextWidth
) {
1423 text
= elideRightKeepExtension(text
, availableTextWidth
);
1424 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1427 TextInfo
*textInfo
= m_textInfo
.value(role
);
1428 textInfo
->staticText
.setText(text
);
1429 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1433 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1434 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1436 // The column after the name should always be aligned on the same x-position independent
1437 // from the expansion-level shown in the name column
1438 x
-= firstColumnInc
- sidePadding();
1439 } else if (isRoleRightAligned(role
)) {
1440 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1445 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1448 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1449 if (m_customTextColor
.isValid()) {
1450 c1
= m_customTextColor
;
1451 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1452 // The detail text colour needs to match the main text (HighlightedText) for the same level
1453 // of readability. We short circuit early here to avoid interpolating with another colour.
1454 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1457 c1
= styleOption().palette
.text().color();
1460 // For the color of the additional info the inactive text color
1461 // is not used as this might lead to unreadable text for some color schemes. Instead
1462 // the text color c1 is slightly mixed with the background color.
1463 const QColor c2
= styleOption().palette
.base().color();
1465 const int p2
= 100 - p1
;
1466 m_additionalInfoTextColor
=
1467 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1470 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1472 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1473 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1474 QPixmap scaledPixmap
= pixmap
;
1475 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1476 scaledPixmap
.setDevicePixelRatio(dpr
);
1477 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1479 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1480 painter
->setPen(Qt::blue
);
1481 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1484 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1488 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1490 const int siblingSize
= size().height();
1491 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1492 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1494 bool isItemSibling
= true;
1496 const QBitArray siblings
= siblingsInformation();
1497 QStyleOption option
;
1498 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1499 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1500 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1501 option
.rect
= siblingRect
;
1502 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1503 if (isItemSibling
) {
1504 option
.state
|= QStyle::State_Item
;
1505 if (m_isExpandable
) {
1506 option
.state
|= QStyle::State_Children
;
1508 if (data().value("isExpanded").toBool()) {
1509 option
.state
|= QStyle::State_Open
;
1511 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1512 isItemSibling
= false;
1514 option
.palette
.setColor(QPalette::Text
, normalColor
);
1517 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1519 siblingRect
.translate(-siblingRect
.width(), 0);
1523 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1525 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1530 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1531 if (m_layout
== DetailsLayout
) {
1532 rect
.setWidth(columnWidth(role
) - rect
.x());
1538 void KStandardItemListWidget::closeRoleEditor()
1540 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1541 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1543 if (m_roleEditor
->hasFocus()) {
1544 // If the editing was not ended by a FocusOut event, we have
1545 // to transfer the keyboard focus back to the KItemListContainer.
1546 scene()->views()[0]->parentWidget()->setFocus();
1549 if (m_oldRoleEditor
) {
1550 m_oldRoleEditor
->deleteLater();
1552 m_oldRoleEditor
= m_roleEditor
;
1553 m_roleEditor
->hide();
1554 m_roleEditor
= nullptr;
1557 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1559 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1560 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1564 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1565 % ":" % QString::number(mode
);
1568 if (!QPixmapCache::find(key
, &pixmap
)) {
1569 QIcon icon
= QIcon::fromTheme(name
);
1570 if (icon
.isNull()) {
1573 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1574 icon
= fallbackIcon
;
1577 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1578 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1579 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1582 // Strangely KFileItem::overlays() returns empty string-values, so
1583 // we need to check first whether an overlay must be drawn at all.
1584 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1585 // assumes that an overlay will be drawn and has some additional
1587 for (const QString
&overlay
: overlays
) {
1588 if (!overlay
.isEmpty()) {
1589 int state
= KIconLoader::DefaultState
;
1595 state
= KIconLoader::ActiveState
;
1597 case QIcon::Disabled
:
1598 state
= KIconLoader::DisabledState
;
1600 case QIcon::Selected
:
1601 state
= KIconLoader::SelectedState
;
1605 // There is at least one overlay, draw all overlays above m_pixmap
1606 // and cancel the check
1607 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1612 QPixmapCache::insert(key
, pixmap
);
1614 pixmap
.setDevicePixelRatio(dpr
);
1619 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1621 const qreal height
= option
.fontMetrics
.ascent();
1622 return QSizeF(height
* 5, height
);
1625 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1627 return option
.padding
* 6;
1630 #include "moc_kstandarditemlistwidget.cpp"