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 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
303 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
305 if (m_highlightEntireRow
!= highlightEntireRow
) {
306 m_highlightEntireRow
= highlightEntireRow
;
307 m_dirtyLayout
= true;
312 bool KStandardItemListWidget::highlightEntireRow() const
314 return m_highlightEntireRow
;
317 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
319 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
320 m_supportsItemExpanding
= supportsItemExpanding
;
321 m_dirtyLayout
= true;
326 bool KStandardItemListWidget::supportsItemExpanding() const
328 return m_supportsItemExpanding
;
331 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
333 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
335 KItemListWidget::paint(painter
, option
, widget
);
337 if (!m_expansionArea
.isEmpty()) {
338 drawSiblingsInformation(painter
);
341 const KItemListStyleOption
&itemListStyleOption
= styleOption();
342 if (isHovered() && !m_pixmap
.isNull()) {
343 if (hoverOpacity() < 1.0) {
345 * Linear interpolation between m_pixmap and m_hoverPixmap.
347 * Note that this cannot be achieved by painting m_hoverPixmap over
348 * m_pixmap, even if the opacities are adjusted. For details see
349 * https://git.reviewboard.kde.org/r/109614/
351 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
352 QPixmap
pixmap1(m_pixmap
.size());
353 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
354 pixmap1
.fill(Qt::transparent
);
356 QPainter
p(&pixmap1
);
357 p
.setOpacity(1.0 - hoverOpacity());
358 p
.drawPixmap(0, 0, m_pixmap
);
361 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
362 QPixmap
pixmap2(pixmap1
.size());
363 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
364 pixmap2
.fill(Qt::transparent
);
366 QPainter
p(&pixmap2
);
367 p
.setOpacity(hoverOpacity());
368 p
.drawPixmap(0, 0, m_hoverPixmap
);
371 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
372 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
373 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
375 QPainter
p(&pixmap1
);
376 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
377 p
.drawPixmap(0, 0, pixmap2
);
380 // Finally paint pixmap1 on the widget
381 drawPixmap(painter
, pixmap1
);
383 drawPixmap(painter
, m_hoverPixmap
);
385 } else if (!m_pixmap
.isNull()) {
386 drawPixmap(painter
, m_pixmap
);
389 painter
->setFont(m_customizedFont
);
390 painter
->setPen(textColor(*widget
));
391 const TextInfo
*textInfo
= m_textInfo
.value("text");
394 // It seems that we can end up here even if m_textInfo does not contain
395 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
396 // this can only happen if the index is negative. This can happen when
397 // the item is about to be removed, see KItemListView::slotItemsRemoved().
398 // TODO: try to reproduce the crash and find a better fix.
402 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
404 bool clipAdditionalInfoBounds
= false;
405 if (m_supportsItemExpanding
) {
406 // Prevent a possible overlapping of the additional-information texts
407 // with the icon. This can happen if the user has minimized the width
408 // of the name-column to a very small value.
409 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
410 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
411 clipAdditionalInfoBounds
= true;
413 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
417 painter
->setPen(m_additionalInfoTextColor
);
418 painter
->setFont(m_customizedFont
);
420 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
421 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
422 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
425 if (!m_rating
.isNull()) {
426 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
427 QPointF pos
= ratingTextInfo
->pos
;
428 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
429 if (align
& Qt::AlignHCenter
) {
430 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
432 painter
->drawPixmap(pos
, m_rating
);
435 if (clipAdditionalInfoBounds
) {
439 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
440 painter
->setBrush(Qt::NoBrush
);
441 painter
->setPen(Qt::green
);
442 painter
->drawRect(m_iconRect
);
444 painter
->setPen(Qt::blue
);
445 painter
->drawRect(m_textRect
);
447 painter
->setPen(Qt::red
);
448 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
449 painter
->drawRect(rect());
453 QRectF
KStandardItemListWidget::iconRect() const
455 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
459 QRectF
KStandardItemListWidget::textRect() const
461 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
465 QRectF
KStandardItemListWidget::textFocusRect() const
467 // In the compact- and details-layout a larger textRect() is returned to be aligned
468 // with the iconRect(). This is useful to have a larger selection/hover-area
469 // when having a quite large icon size but only one line of text. Still the
470 // focus rectangle should be shown as narrow as possible around the text.
472 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
475 case CompactLayout
: {
476 QRectF rect
= m_textRect
;
477 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
478 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
479 rect
.setTop(topText
->pos
.y());
480 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
484 case DetailsLayout
: {
485 QRectF rect
= m_textRect
;
486 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
487 rect
.setTop(textInfo
->pos
.y());
488 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
490 const KItemListStyleOption
&option
= styleOption();
491 if (option
.extendedSelectionRegion
) {
492 const QString text
= textInfo
->staticText
.text();
493 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
506 QRectF
KStandardItemListWidget::selectionRect() const
508 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
515 case DetailsLayout
: {
516 const int padding
= styleOption().padding
;
517 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
518 QRectF result
= adjustedIconRect
| m_textRect
;
519 if (m_highlightEntireRow
) {
520 result
.setRight(m_columnWidthSum
+ sidePadding());
533 QRectF
KStandardItemListWidget::expansionToggleRect() const
535 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
536 return m_isExpandable
? m_expansionArea
: QRectF();
539 QRectF
KStandardItemListWidget::selectionToggleRect() const
541 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
543 const int widgetIconSize
= iconSize();
544 int toggleSize
= KIconLoader::SizeSmall
;
545 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
546 toggleSize
= KIconLoader::SizeMedium
;
547 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
548 toggleSize
= KIconLoader::SizeSmallMedium
;
551 QPointF pos
= iconRect().topLeft();
553 // If the selection toggle has a very small distance to the
554 // widget borders, the size of the selection toggle will get
555 // increased to prevent an accidental clicking of the item
556 // when trying to hit the toggle.
557 const int widgetHeight
= size().height();
558 const int widgetWidth
= size().width();
559 const int minMargin
= 2;
561 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
562 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
563 toggleSize
= widgetHeight
;
566 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
567 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
568 toggleSize
= widgetWidth
;
572 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
575 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
577 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
578 if (m_layout
!= DetailsLayout
) {
582 // Only return the content of the text-column as pixmap
583 const int leftClip
= m_pixmapPos
.x();
585 const TextInfo
*textInfo
= m_textInfo
.value("text");
586 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
588 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
589 clippedPixmap
.fill(Qt::transparent
);
591 QPainter
painter(&clippedPixmap
);
592 painter
.drawPixmap(-leftClip
, 0, pixmap
);
594 return clippedPixmap
;
597 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
599 return new KStandardItemListWidgetInformant();
602 void KStandardItemListWidget::invalidateCache()
604 m_dirtyLayout
= true;
605 m_dirtyContent
= true;
608 void KStandardItemListWidget::invalidateIconCache()
610 m_dirtyContent
= true;
611 m_dirtyContentRoles
.insert("iconPixmap");
612 m_dirtyContentRoles
.insert("iconOverlays");
615 void KStandardItemListWidget::refreshCache()
619 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
625 bool KStandardItemListWidget::isHidden() const
630 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
635 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
637 return QPalette::Text
;
640 void KStandardItemListWidget::setTextColor(const QColor
&color
)
642 if (color
!= m_customTextColor
) {
643 m_customTextColor
= color
;
644 updateAdditionalInfoTextColor();
649 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
653 return m_additionalInfoTextColor
;
654 } else if (m_customTextColor
.isValid()) {
655 return m_customTextColor
;
659 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
660 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
661 return styleOption().palette
.color(group
, role
);
664 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
667 m_dirtyContent
= true;
671 QPixmap
KStandardItemListWidget::overlay() const
676 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
678 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
681 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
685 m_dirtyContent
= true;
687 QSet
<QByteArray
> dirtyRoles
;
688 if (roles
.isEmpty()) {
689 const auto visibleRoles
= this->visibleRoles();
690 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
695 // The URL might have changed (i.e., if the sort order of the items has
696 // been changed). Therefore, the "is cut" state must be updated.
697 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
698 const QUrl itemUrl
= data().value("url").toUrl();
699 m_isCut
= clipboard
->isCut(itemUrl
);
701 // The icon-state might depend from other roles and hence is
702 // marked as dirty whenever a role has been changed
703 dirtyRoles
.insert("iconPixmap");
704 dirtyRoles
.insert("iconName");
706 QSetIterator
<QByteArray
> it(dirtyRoles
);
707 while (it
.hasNext()) {
708 const QByteArray
&role
= it
.next();
709 m_dirtyContentRoles
.insert(role
);
713 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
716 m_sortedVisibleRoles
= current
;
717 m_dirtyLayout
= true;
720 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
725 m_dirtyLayout
= true;
728 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
731 m_dirtyLayout
= true;
734 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
736 KItemListWidget::styleOptionChanged(current
, previous
);
738 updateAdditionalInfoTextColor();
739 m_dirtyLayout
= true;
742 void KStandardItemListWidget::hoveredChanged(bool hovered
)
745 m_dirtyLayout
= true;
748 void KStandardItemListWidget::selectedChanged(bool selected
)
751 updateAdditionalInfoTextColor();
752 m_dirtyContent
= true;
755 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
759 m_dirtyLayout
= true;
762 int KStandardItemListWidget::selectionLength(const QString
&text
) const
764 return text
.length();
767 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
771 QGraphicsView
*parent
= scene()->views()[0];
772 if (current
.isEmpty() || !parent
|| current
!= "text") {
774 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
776 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
777 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
779 if (m_oldRoleEditor
) {
780 m_oldRoleEditor
->deleteLater();
782 m_oldRoleEditor
= m_roleEditor
;
783 m_roleEditor
->hide();
784 m_roleEditor
= nullptr;
789 Q_ASSERT(!m_roleEditor
);
791 const TextInfo
*textInfo
= m_textInfo
.value("text");
793 m_roleEditor
= new KItemListRoleEditor(parent
);
794 m_roleEditor
->setRole(current
);
795 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
796 m_roleEditor
->setFont(styleOption().font
);
798 const QString text
= data().value(current
).toString();
799 m_roleEditor
->setPlainText(text
);
801 QTextOption textOption
= textInfo
->staticText
.textOption();
802 m_roleEditor
->document()->setDefaultTextOption(textOption
);
804 const int textSelectionLength
= selectionLength(text
);
806 if (textSelectionLength
> 0) {
807 QTextCursor cursor
= m_roleEditor
->textCursor();
808 cursor
.movePosition(QTextCursor::StartOfBlock
);
809 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
810 m_roleEditor
->setTextCursor(cursor
);
813 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
814 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
816 // Adjust the geometry of the editor
817 QRectF rect
= roleEditingRect(current
);
818 const int frameWidth
= m_roleEditor
->frameWidth();
819 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
820 rect
.translate(pos());
821 if (rect
.right() > parent
->width()) {
822 rect
.setWidth(parent
->width() - rect
.left());
824 m_roleEditor
->setGeometry(rect
.toRect());
825 m_roleEditor
->autoAdjustSize();
826 m_roleEditor
->show();
827 m_roleEditor
->setFocus();
830 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
832 KItemListWidget::iconSizeChanged(current
, previous
);
834 invalidateIconCache();
835 triggerCacheRefreshing();
839 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
842 setEditedRole(QByteArray());
843 Q_ASSERT(!m_roleEditor
);
846 KItemListWidget::resizeEvent(event
);
848 m_dirtyLayout
= true;
851 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
853 KItemListWidget::showEvent(event
);
855 // Listen to changes of the clipboard to mark the item as cut/uncut
856 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
858 const QUrl itemUrl
= data().value("url").toUrl();
859 m_isCut
= clipboard
->isCut(itemUrl
);
861 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
864 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
866 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
868 KItemListWidget::hideEvent(event
);
871 bool KStandardItemListWidget::event(QEvent
*event
)
873 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
874 m_dirtyContent
= true;
877 return KItemListWidget::event(event
);
880 void KStandardItemListWidget::finishRoleEditing()
882 if (!editedRole().isEmpty() && m_roleEditor
) {
883 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
887 void KStandardItemListWidget::slotCutItemsChanged()
889 const QUrl itemUrl
= data().value("url").toUrl();
890 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
891 if (m_isCut
!= isCut
) {
893 m_pixmap
= QPixmap();
894 m_dirtyContent
= true;
899 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
902 Q_EMIT
roleEditingCanceled(index(), role
, value
);
903 setEditedRole(QByteArray());
906 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
909 Q_EMIT
roleEditingFinished(index(), role
, value
);
910 setEditedRole(QByteArray());
913 void KStandardItemListWidget::triggerCacheRefreshing()
915 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
921 const QHash
<QByteArray
, QVariant
> values
= data();
922 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
923 m_isHidden
= isHidden();
924 m_customizedFont
= customizedFont(styleOption().font
);
925 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
926 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
927 return sum
+ columnWidth(role
);
930 updateExpansionArea();
935 m_dirtyLayout
= false;
936 m_dirtyContent
= false;
937 m_dirtyContentRoles
.clear();
940 void KStandardItemListWidget::updateExpansionArea()
942 if (m_supportsItemExpanding
) {
943 const QHash
<QByteArray
, QVariant
> values
= data();
944 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
945 if (expandedParentsCount
>= 0) {
946 const int widgetIconSize
= iconSize();
947 const qreal widgetHeight
= size().height();
948 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
949 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
951 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
952 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
957 m_expansionArea
= QRectF();
960 void KStandardItemListWidget::updatePixmapCache()
962 // Precondition: Requires already updated m_textPos values to calculate
963 // the remaining height when the alignment is vertical.
965 const QSizeF widgetSize
= size();
966 const bool iconOnTop
= (m_layout
== IconsLayout
);
967 const KItemListStyleOption
&option
= styleOption();
968 const qreal padding
= option
.padding
;
969 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
971 const int widgetIconSize
= iconSize();
972 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
973 const int maxIconHeight
= widgetIconSize
;
975 const QHash
<QByteArray
, QVariant
> values
= data();
977 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
978 if (!updatePixmap
&& m_dirtyContent
) {
979 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
980 || m_dirtyContentRoles
.contains("iconOverlays");
984 m_pixmap
= QPixmap();
986 int sequenceIndex
= hoverSequenceIndex();
988 if (values
.contains("hoverSequencePixmaps")) {
989 // Use one of the hover sequence pixmaps instead of the default
992 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
994 if (values
.contains("hoverSequenceWraparoundPoint")) {
995 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
997 sequenceIndex
%= static_cast<int>(wap
);
1001 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1003 if (loadedIndex
!= 0) {
1004 m_pixmap
= pixmaps
[loadedIndex
];
1008 if (m_pixmap
.isNull()) {
1009 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1012 if (m_pixmap
.isNull()) {
1013 // Use the icon that fits to the MIME-type
1014 QString iconName
= values
["iconName"].toString();
1015 if (iconName
.isEmpty()) {
1016 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1017 // use a generic icon as fallback
1018 iconName
= QStringLiteral("unknown");
1020 const QStringList overlays
= values
["iconOverlays"].toStringList();
1021 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1022 m_pixmap
= pixmapForIcon(iconName
,
1025 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1027 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1028 // A custom pixmap has been applied. Assure that the pixmap
1029 // is scaled to the maximum available size.
1030 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1033 if (m_pixmap
.isNull()) {
1034 m_hoverPixmap
= QPixmap();
1039 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1040 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1044 KIconEffect::semiTransparent(m_pixmap
);
1047 if (m_layout
== IconsLayout
&& isSelected()) {
1048 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1049 QImage image
= m_pixmap
.toImage();
1050 if (image
.isNull()) {
1051 m_hoverPixmap
= QPixmap();
1054 KIconEffect::colorize(image
, color
, 0.8f
);
1055 m_pixmap
= QPixmap::fromImage(image
);
1059 if (!m_overlay
.isNull()) {
1060 QPainter
painter(&m_pixmap
);
1061 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1064 int scaledIconSize
= 0;
1066 const TextInfo
*textInfo
= m_textInfo
.value("text");
1067 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1069 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1070 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1071 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1074 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1075 const int maxScaledIconHeight
= scaledIconSize
;
1077 m_scaledPixmapSize
= m_pixmap
.size();
1078 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1079 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1082 // Center horizontally and align on bottom within the icon-area
1083 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1084 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1086 // Center horizontally and vertically within the icon-area
1087 const TextInfo
*textInfo
= m_textInfo
.value("text");
1088 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1090 // Derive icon's vertical center from the center of the text frame, including
1091 // any necessary adjustment if the font's midline is offset from the frame center
1092 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1093 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1096 if (m_layout
== IconsLayout
) {
1097 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1099 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1100 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1101 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1102 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1103 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1106 // Prepare the pixmap that is used when the item gets hovered
1108 m_hoverPixmap
= m_pixmap
;
1109 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1110 // In the KIconLoader terminology, active = hover.
1111 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1112 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1114 m_hoverPixmap
= m_pixmap
;
1116 } else if (hoverOpacity() <= 0.0) {
1117 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1118 m_hoverPixmap
= QPixmap();
1122 void KStandardItemListWidget::updateTextsCache()
1124 QTextOption textOption
;
1127 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1128 textOption
.setAlignment(Qt::AlignHCenter
);
1132 textOption
.setAlignment(Qt::AlignLeft
);
1133 textOption
.setWrapMode(QTextOption::NoWrap
);
1140 qDeleteAll(m_textInfo
);
1142 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1143 TextInfo
*textInfo
= new TextInfo();
1144 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1145 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1146 textInfo
->staticText
.setTextOption(textOption
);
1147 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1152 updateIconsLayoutTextCache();
1155 updateCompactLayoutTextCache();
1158 updateDetailsLayoutTextCache();
1165 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1166 if (ratingTextInfo
) {
1167 // The text of the rating-role has been set to empty to get
1168 // replaced by a rating-image showing the rating as stars.
1169 const KItemListStyleOption
&option
= styleOption();
1170 QSizeF ratingSize
= preferredRatingSize(option
);
1172 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1173 if (ratingSize
.width() > availableWidth
) {
1174 ratingSize
.rwidth() = availableWidth
;
1176 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1177 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1178 m_rating
.setDevicePixelRatio(dpr
);
1179 m_rating
.fill(Qt::transparent
);
1181 QPainter
painter(&m_rating
);
1182 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1183 const int rating
= data().value("rating").toInt();
1184 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1185 } else if (!m_rating
.isNull()) {
1186 m_rating
= QPixmap();
1190 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1192 const auto extensionIndex
= text
.lastIndexOf('.');
1193 if (extensionIndex
!= -1) {
1194 // has file extension
1195 const auto extensionLength
= text
.length() - extensionIndex
;
1196 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1197 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1198 // if we have room to display the file extension and the extension is not too long
1199 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1200 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1201 ret
.append(text
.rightRef(extensionLength
));
1203 ret
.append(QStringView(text
).right(extensionLength
));
1208 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1211 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1213 QString
escaped(text
);
1215 const QChar
returnSymbol(0x21b5);
1216 escaped
.replace('\n', returnSymbol
);
1221 void KStandardItemListWidget::updateIconsLayoutTextCache()
1228 // might get wrapped above
1230 // Additional role 1
1231 // Additional role 2
1233 const QHash
<QByteArray
, QVariant
> values
= data();
1235 const KItemListStyleOption
&option
= styleOption();
1236 const qreal padding
= option
.padding
;
1237 const qreal maxWidth
= size().width() - 2 * padding
;
1238 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1240 // Initialize properties for the "text" role. It will be used as anchor
1241 // for initializing the position of the other roles.
1242 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1243 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1244 nameTextInfo
->staticText
.setText(nameText
);
1246 // Calculate the number of lines required for the name and the required width
1247 qreal nameWidth
= 0;
1248 qreal nameHeight
= 0;
1251 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1252 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1253 layout
.beginLayout();
1254 int nameLineIndex
= 0;
1255 while ((line
= layout
.createLine()).isValid()) {
1256 line
.setLineWidth(maxWidth
);
1257 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1258 nameHeight
+= line
.height();
1261 if (nameLineIndex
== option
.maxTextLines
) {
1262 // The maximum number of textlines has been reached. If this is
1263 // the case provide an elided text if necessary.
1264 const int textLength
= line
.textStart() + line
.textLength();
1265 if (textLength
< nameText
.length()) {
1266 // Elide the last line of the text
1267 qreal elidingWidth
= maxWidth
;
1268 qreal lastLineWidth
;
1270 QString lastTextLine
= nameText
.mid(line
.textStart());
1271 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1272 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1273 nameTextInfo
->staticText
.setText(elidedText
);
1275 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1277 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1278 // to avoid problems related to different width calculation code paths
1279 // within Qt. (see bug 337104)
1280 elidingWidth
-= 1.0;
1281 } while (lastLineWidth
> maxWidth
);
1283 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1290 // Use one line for each additional information
1291 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1292 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1293 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1295 // Calculate the position for each additional information
1296 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1297 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1298 if (role
== "text") {
1302 const QString text
= roleText(role
, values
);
1303 TextInfo
*textInfo
= m_textInfo
.value(role
);
1304 textInfo
->staticText
.setText(text
);
1306 qreal requiredWidth
= 0;
1308 QTextLayout
layout(text
, m_customizedFont
);
1309 QTextOption textOption
;
1310 textOption
.setWrapMode(QTextOption::NoWrap
);
1311 layout
.setTextOption(textOption
);
1313 layout
.beginLayout();
1314 QTextLine textLine
= layout
.createLine();
1315 if (textLine
.isValid()) {
1316 textLine
.setLineWidth(maxWidth
);
1317 requiredWidth
= textLine
.naturalTextWidth();
1318 if (requiredWidth
> maxWidth
) {
1319 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1320 textInfo
->staticText
.setText(elidedText
);
1321 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1322 } else if (role
== "rating") {
1323 // Use the width of the rating pixmap, because the rating text is empty.
1324 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1329 textInfo
->pos
= QPointF(padding
, y
);
1330 textInfo
->staticText
.setTextWidth(maxWidth
);
1332 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1334 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1335 if (!textRect
.isEmpty()) {
1336 m_textRect
|= textRect
;
1342 // Add a padding to the text rectangle
1343 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1346 void KStandardItemListWidget::updateCompactLayoutTextCache()
1348 // +------+ Name role
1349 // | Icon | Additional role 1
1350 // +------+ Additional role 2
1352 const QHash
<QByteArray
, QVariant
> values
= data();
1354 const KItemListStyleOption
&option
= styleOption();
1355 const qreal widgetHeight
= size().height();
1356 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1357 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1359 qreal maximumRequiredTextWidth
= 0;
1360 const qreal x
= option
.padding
* 3 + iconSize();
1361 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1362 const qreal maxWidth
= size().width() - x
- option
.padding
;
1363 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1364 const QString text
= escapeString(roleText(role
, values
));
1365 TextInfo
*textInfo
= m_textInfo
.value(role
);
1366 textInfo
->staticText
.setText(text
);
1368 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1369 if (requiredWidth
> maxWidth
) {
1370 requiredWidth
= maxWidth
;
1371 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1372 textInfo
->staticText
.setText(elidedText
);
1375 textInfo
->pos
= QPointF(x
, y
);
1376 textInfo
->staticText
.setTextWidth(maxWidth
);
1378 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1383 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1386 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1388 // Precondition: Requires already updated m_expansionArea
1389 // to determine the left position.
1392 // | Icon | Name role Additional role 1 Additional role 2
1394 m_textRect
= QRectF();
1396 const KItemListStyleOption
&option
= styleOption();
1397 const QHash
<QByteArray
, QVariant
> values
= data();
1399 const qreal widgetHeight
= size().height();
1400 const int fontHeight
= m_customizedFontMetrics
.height();
1402 const qreal columnWidthInc
= columnPadding(option
);
1403 qreal firstColumnInc
= iconSize();
1404 if (m_supportsItemExpanding
) {
1405 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1407 firstColumnInc
+= option
.padding
+ sidePadding();
1410 qreal x
= firstColumnInc
;
1411 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1413 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1414 QString text
= roleText(role
, values
);
1416 // Elide the text in case it does not fit into the available column-width
1417 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1418 const qreal roleWidth
= columnWidth(role
);
1419 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1421 const bool isTextRole
= (role
== "text");
1423 text
= escapeString(text
);
1424 availableTextWidth
-= firstColumnInc
- sidePadding();
1427 if (requiredWidth
> availableTextWidth
) {
1428 text
= elideRightKeepExtension(text
, availableTextWidth
);
1429 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1432 TextInfo
*textInfo
= m_textInfo
.value(role
);
1433 textInfo
->staticText
.setText(text
);
1434 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1438 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1439 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1441 // The column after the name should always be aligned on the same x-position independent
1442 // from the expansion-level shown in the name column
1443 x
-= firstColumnInc
- sidePadding();
1444 } else if (isRoleRightAligned(role
)) {
1445 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1450 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1453 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1454 if (m_customTextColor
.isValid()) {
1455 c1
= m_customTextColor
;
1456 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1457 // The detail text colour needs to match the main text (HighlightedText) for the same level
1458 // of readability. We short circuit early here to avoid interpolating with another colour.
1459 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1462 c1
= styleOption().palette
.text().color();
1465 // For the color of the additional info the inactive text color
1466 // is not used as this might lead to unreadable text for some color schemes. Instead
1467 // the text color c1 is slightly mixed with the background color.
1468 const QColor c2
= styleOption().palette
.base().color();
1470 const int p2
= 100 - p1
;
1471 m_additionalInfoTextColor
=
1472 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1475 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1477 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1478 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1479 QPixmap scaledPixmap
= pixmap
;
1480 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1481 scaledPixmap
.setDevicePixelRatio(dpr
);
1482 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1484 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1485 painter
->setPen(Qt::blue
);
1486 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1489 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1493 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1495 const int siblingSize
= size().height();
1496 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1497 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1499 bool isItemSibling
= true;
1501 const QBitArray siblings
= siblingsInformation();
1502 QStyleOption option
;
1503 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1504 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1505 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1506 option
.rect
= siblingRect
;
1507 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1508 if (isItemSibling
) {
1509 option
.state
|= QStyle::State_Item
;
1510 if (m_isExpandable
) {
1511 option
.state
|= QStyle::State_Children
;
1513 if (data().value("isExpanded").toBool()) {
1514 option
.state
|= QStyle::State_Open
;
1516 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1517 isItemSibling
= false;
1519 option
.palette
.setColor(QPalette::Text
, normalColor
);
1522 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1524 siblingRect
.translate(-siblingRect
.width(), 0);
1528 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1530 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1535 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1536 if (m_layout
== DetailsLayout
) {
1537 rect
.setWidth(columnWidth(role
) - rect
.x());
1543 void KStandardItemListWidget::closeRoleEditor()
1545 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1546 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1548 if (m_roleEditor
->hasFocus()) {
1549 // If the editing was not ended by a FocusOut event, we have
1550 // to transfer the keyboard focus back to the KItemListContainer.
1551 scene()->views()[0]->parentWidget()->setFocus();
1554 if (m_oldRoleEditor
) {
1555 m_oldRoleEditor
->deleteLater();
1557 m_oldRoleEditor
= m_roleEditor
;
1558 m_roleEditor
->hide();
1559 m_roleEditor
= nullptr;
1562 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1564 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1565 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1569 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1570 % ":" % QString::number(mode
);
1573 if (!QPixmapCache::find(key
, &pixmap
)) {
1574 QIcon icon
= QIcon::fromTheme(name
);
1575 if (icon
.isNull()) {
1578 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1579 icon
= fallbackIcon
;
1582 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1583 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1584 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1587 // Strangely KFileItem::overlays() returns empty string-values, so
1588 // we need to check first whether an overlay must be drawn at all.
1589 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1590 // assumes that an overlay will be drawn and has some additional
1592 for (const QString
&overlay
: overlays
) {
1593 if (!overlay
.isEmpty()) {
1594 int state
= KIconLoader::DefaultState
;
1600 state
= KIconLoader::ActiveState
;
1602 case QIcon::Disabled
:
1603 state
= KIconLoader::DisabledState
;
1605 case QIcon::Selected
:
1606 state
= KIconLoader::SelectedState
;
1610 // There is at least one overlay, draw all overlays above m_pixmap
1611 // and cancel the check
1612 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1617 QPixmapCache::insert(key
, pixmap
);
1619 pixmap
.setDevicePixelRatio(dpr
);
1624 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1626 const qreal height
= option
.fontMetrics
.ascent();
1627 return QSizeF(height
* 5, height
);
1630 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1632 return option
.padding
* 6;
1635 #include "moc_kstandarditemlistwidget.cpp"