2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QPixmapCache>
25 #include <QStyleOption>
27 // #define KSTANDARDITEMLISTWIDGET_DEBUG
29 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
30 KItemListWidgetInformant()
34 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
38 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
40 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
41 case KStandardItemListView::IconsLayout
:
42 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
45 case KStandardItemListView::CompactLayout
:
46 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
49 case KStandardItemListView::DetailsLayout
:
50 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
59 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
61 const KItemListView
* view
) const
63 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
64 const KItemListStyleOption
& option
= view
->styleOption();
66 const QString text
= roleText(role
, values
);
67 qreal width
= KStandardItemListWidget::columnPadding(option
);
69 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
70 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
72 if (role
== "rating") {
73 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
75 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
76 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
78 width
+= fontMetrics
.horizontalAdvance(text
);
81 if (view
->supportsItemExpanding()) {
82 // Increase the width by the expansion-toggle and the current expansion level
83 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
84 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
85 width
+= (expandedParentsCount
+ 1) * height
;
88 // Increase the width by the required space for the icon
89 width
+= option
.padding
* 2 + option
.iconSize
;
96 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
* view
) const
98 return view
->model()->data(index
).value("text").toString();
101 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
* view
) const
108 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
109 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
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
125 const KItemListStyleOption
& option
= view
->styleOption();
126 const QFont
& normalFont
= option
.font
;
127 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
129 const qreal itemWidth
= view
->itemSize().width();
130 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
131 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
132 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
134 const QFont linkFont
= customizedFontForLinks(normalFont
);
136 QTextOption
textOption(Qt::AlignHCenter
);
137 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
139 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
140 if (logicalHeightHints
.at(index
).first
> 0.0) {
144 // If the current item is a link, we use the customized link font instead of the normal font.
145 const QFont
& font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
147 const QString
& text
= KStringHandler::preProcessWrap(itemText(index
, view
));
149 // Calculate the number of lines required for wrapping the name
150 qreal textHeight
= 0;
151 QTextLayout
layout(text
, font
);
152 layout
.setTextOption(textOption
);
153 layout
.beginLayout();
156 bool isElided
= false;
157 while ((line
= layout
.createLine()).isValid()) {
158 line
.setLineWidth(maxWidth
);
159 line
.naturalTextWidth();
160 textHeight
+= line
.height();
163 if (lineCount
== option
.maxTextLines
) {
164 isElided
= layout
.createLine().isValid();
170 // Add one line for each additional information
171 textHeight
+= additionalRolesSpacing
;
173 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
174 logicalHeightHints
[index
].second
= isElided
;
177 logicalWidthHint
= itemWidth
;
180 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
182 const KItemListStyleOption
& option
= view
->styleOption();
183 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
184 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
186 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
187 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
188 const qreal maxWidth
= option
.maxTextWidth
;
189 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
190 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
192 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
194 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
195 if (logicalHeightHints
.at(index
).first
> 0.0) {
199 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
200 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
202 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
203 // to show all roles without horizontal clipping.
204 qreal maximumRequiredWidth
= 0.0;
206 if (showOnlyTextRole
) {
207 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
209 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
210 for (const QByteArray
& role
: visibleRoles
) {
211 const QString
& text
= roleText(role
, values
);
212 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
213 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
217 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
218 if (maxWidth
> 0 && width
> maxWidth
) {
222 logicalHeightHints
[index
].first
= width
;
225 logicalWidthHint
= height
;
228 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
230 const KItemListStyleOption
& option
= view
->styleOption();
231 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
232 logicalHeightHints
.fill(std::make_pair(height
, false));
233 logicalWidthHint
= -1.0;
236 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
237 KItemListWidget(informant
, parent
),
242 m_customizedFontMetrics(m_customizedFont
),
243 m_isExpandable(false),
244 m_supportsItemExpanding(false),
246 m_dirtyContent(true),
247 m_dirtyContentRoles(),
248 m_layout(IconsLayout
),
251 m_scaledPixmapSize(),
256 m_sortedVisibleRoles(),
259 m_additionalInfoTextColor(),
262 m_roleEditor(nullptr),
263 m_oldRoleEditor(nullptr)
267 KStandardItemListWidget::~KStandardItemListWidget()
269 qDeleteAll(m_textInfo
);
273 m_roleEditor
->deleteLater();
276 if (m_oldRoleEditor
) {
277 m_oldRoleEditor
->deleteLater();
281 void KStandardItemListWidget::setLayout(Layout layout
)
283 if (m_layout
!= layout
) {
285 m_dirtyLayout
= true;
286 updateAdditionalInfoTextColor();
291 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
296 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
) {
297 if (m_highlightEntireRow
!= highlightEntireRow
) {
298 m_highlightEntireRow
= highlightEntireRow
;
299 m_dirtyLayout
= true;
304 bool KStandardItemListWidget::highlightEntireRow() const {
305 return m_highlightEntireRow
;
308 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
310 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
311 m_supportsItemExpanding
= supportsItemExpanding
;
312 m_dirtyLayout
= true;
317 bool KStandardItemListWidget::supportsItemExpanding() const
319 return m_supportsItemExpanding
;
322 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
324 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
326 KItemListWidget::paint(painter
, option
, widget
);
328 if (!m_expansionArea
.isEmpty()) {
329 drawSiblingsInformation(painter
);
332 const KItemListStyleOption
& itemListStyleOption
= styleOption();
333 if (isHovered() && !m_pixmap
.isNull()) {
334 if (hoverOpacity() < 1.0) {
336 * Linear interpolation between m_pixmap and m_hoverPixmap.
338 * Note that this cannot be achieved by painting m_hoverPixmap over
339 * m_pixmap, even if the opacities are adjusted. For details see
340 * https://git.reviewboard.kde.org/r/109614/
342 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
343 QPixmap
pixmap1(m_pixmap
.size());
344 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
345 pixmap1
.fill(Qt::transparent
);
347 QPainter
p(&pixmap1
);
348 p
.setOpacity(1.0 - hoverOpacity());
349 p
.drawPixmap(0, 0, m_pixmap
);
352 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
353 QPixmap
pixmap2(pixmap1
.size());
354 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
355 pixmap2
.fill(Qt::transparent
);
357 QPainter
p(&pixmap2
);
358 p
.setOpacity(hoverOpacity());
359 p
.drawPixmap(0, 0, m_hoverPixmap
);
362 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
363 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
364 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
366 QPainter
p(&pixmap1
);
367 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
368 p
.drawPixmap(0, 0, pixmap2
);
371 // Finally paint pixmap1 on the widget
372 drawPixmap(painter
, pixmap1
);
374 drawPixmap(painter
, m_hoverPixmap
);
376 } else if (!m_pixmap
.isNull()) {
377 drawPixmap(painter
, m_pixmap
);
380 painter
->setFont(m_customizedFont
);
381 painter
->setPen(textColor());
382 const TextInfo
* textInfo
= m_textInfo
.value("text");
385 // It seems that we can end up here even if m_textInfo does not contain
386 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
387 // this can only happen if the index is negative. This can happen when
388 // the item is about to be removed, see KItemListView::slotItemsRemoved().
389 // TODO: try to reproduce the crash and find a better fix.
393 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
395 bool clipAdditionalInfoBounds
= false;
396 if (m_supportsItemExpanding
) {
397 // Prevent a possible overlapping of the additional-information texts
398 // with the icon. This can happen if the user has minimized the width
399 // of the name-column to a very small value.
400 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
401 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
402 clipAdditionalInfoBounds
= true;
404 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
408 painter
->setPen(m_additionalInfoTextColor
);
409 painter
->setFont(m_customizedFont
);
411 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
412 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
413 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
416 if (!m_rating
.isNull()) {
417 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
418 QPointF pos
= ratingTextInfo
->pos
;
419 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
420 if (align
& Qt::AlignHCenter
) {
421 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
423 painter
->drawPixmap(pos
, m_rating
);
426 if (clipAdditionalInfoBounds
) {
430 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
431 painter
->setBrush(Qt::NoBrush
);
432 painter
->setPen(Qt::green
);
433 painter
->drawRect(m_iconRect
);
435 painter
->setPen(Qt::blue
);
436 painter
->drawRect(m_textRect
);
438 painter
->setPen(Qt::red
);
439 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
440 painter
->drawRect(rect());
444 QRectF
KStandardItemListWidget::iconRect() const
446 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
450 QRectF
KStandardItemListWidget::textRect() const
452 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
456 QRectF
KStandardItemListWidget::textFocusRect() const
458 // In the compact- and details-layout a larger textRect() is returned to be aligned
459 // with the iconRect(). This is useful to have a larger selection/hover-area
460 // when having a quite large icon size but only one line of text. Still the
461 // focus rectangle should be shown as narrow as possible around the text.
463 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
466 case CompactLayout
: {
467 QRectF rect
= m_textRect
;
468 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
469 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
470 rect
.setTop(topText
->pos
.y());
471 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
475 case DetailsLayout
: {
476 QRectF rect
= m_textRect
;
477 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
478 rect
.setTop(textInfo
->pos
.y());
479 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
481 const KItemListStyleOption
& option
= styleOption();
482 if (option
.extendedSelectionRegion
) {
483 const QString text
= textInfo
->staticText
.text();
484 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
497 QRectF
KStandardItemListWidget::selectionRect() const
499 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
506 case DetailsLayout
: {
507 const int padding
= styleOption().padding
;
508 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
509 QRectF result
= adjustedIconRect
| m_textRect
;
510 if (m_highlightEntireRow
) {
511 result
.setRight(m_columnWidthSum
+ sidePadding());
524 QRectF
KStandardItemListWidget::expansionToggleRect() const
526 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
527 return m_isExpandable
? m_expansionArea
: QRectF();
530 QRectF
KStandardItemListWidget::selectionToggleRect() const
532 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
534 const int widgetIconSize
= iconSize();
535 int toggleSize
= KIconLoader::SizeSmall
;
536 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
537 toggleSize
= KIconLoader::SizeMedium
;
538 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
539 toggleSize
= KIconLoader::SizeSmallMedium
;
542 QPointF pos
= iconRect().topLeft();
544 // If the selection toggle has a very small distance to the
545 // widget borders, the size of the selection toggle will get
546 // increased to prevent an accidental clicking of the item
547 // when trying to hit the toggle.
548 const int widgetHeight
= size().height();
549 const int widgetWidth
= size().width();
550 const int minMargin
= 2;
552 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
553 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
554 toggleSize
= widgetHeight
;
557 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
558 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
559 toggleSize
= widgetWidth
;
563 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
566 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
569 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
570 if (m_layout
!= DetailsLayout
) {
574 // Only return the content of the text-column as pixmap
575 const int leftClip
= m_pixmapPos
.x();
577 const TextInfo
* textInfo
= m_textInfo
.value("text");
578 const int rightClip
= textInfo
->pos
.x() +
579 textInfo
->staticText
.size().width() +
580 2 * styleOption().padding
;
582 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
583 clippedPixmap
.fill(Qt::transparent
);
585 QPainter
painter(&clippedPixmap
);
586 painter
.drawPixmap(-leftClip
, 0, pixmap
);
588 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
648 return m_additionalInfoTextColor
;
649 } else if (m_customTextColor
.isValid()) {
650 return m_customTextColor
;
654 const QPalette::ColorGroup group
= isActiveWindow() ? 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
672 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
673 const QHash
<QByteArray
, QVariant
>& values
) const
675 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
678 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
679 const QSet
<QByteArray
>& roles
)
683 m_dirtyContent
= true;
685 QSet
<QByteArray
> dirtyRoles
;
686 if (roles
.isEmpty()) {
687 const auto visibleRoles
= this->visibleRoles();
688 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
693 // The URL might have changed (i.e., if the sort order of the items has
694 // been changed). Therefore, the "is cut" state must be updated.
695 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
696 const QUrl itemUrl
= data().value("url").toUrl();
697 m_isCut
= clipboard
->isCut(itemUrl
);
699 // The icon-state might depend from other roles and hence is
700 // marked as dirty whenever a role has been changed
701 dirtyRoles
.insert("iconPixmap");
702 dirtyRoles
.insert("iconName");
704 QSetIterator
<QByteArray
> it(dirtyRoles
);
705 while (it
.hasNext()) {
706 const QByteArray
& role
= it
.next();
707 m_dirtyContentRoles
.insert(role
);
711 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
712 const QList
<QByteArray
>& previous
)
715 m_sortedVisibleRoles
= current
;
716 m_dirtyLayout
= true;
719 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
726 m_dirtyLayout
= true;
729 void KStandardItemListWidget::sidePaddingChanged(qreal padding
) {
731 m_dirtyLayout
= true;
734 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
735 const KItemListStyleOption
& previous
)
737 KItemListWidget::styleOptionChanged(current
, previous
);
739 updateAdditionalInfoTextColor();
740 m_dirtyLayout
= true;
743 void KStandardItemListWidget::hoveredChanged(bool hovered
)
746 m_dirtyLayout
= true;
749 void KStandardItemListWidget::selectedChanged(bool selected
)
752 updateAdditionalInfoTextColor();
753 m_dirtyContent
= true;
756 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
760 m_dirtyLayout
= true;
763 int KStandardItemListWidget::selectionLength(const QString
& text
) const
765 return text
.length();
768 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
772 QGraphicsView
* parent
= scene()->views()[0];
773 if (current
.isEmpty() || !parent
|| current
!= "text") {
775 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
777 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
778 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
779 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
780 this, &KStandardItemListWidget::slotRoleEditingFinished
);
782 if (m_oldRoleEditor
) {
783 m_oldRoleEditor
->deleteLater();
785 m_oldRoleEditor
= m_roleEditor
;
786 m_roleEditor
->hide();
787 m_roleEditor
= nullptr;
792 Q_ASSERT(!m_roleEditor
);
794 const TextInfo
* textInfo
= m_textInfo
.value("text");
796 m_roleEditor
= new KItemListRoleEditor(parent
);
797 m_roleEditor
->setRole(current
);
798 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
799 m_roleEditor
->setFont(styleOption().font
);
801 const QString text
= data().value(current
).toString();
802 m_roleEditor
->setPlainText(text
);
804 QTextOption textOption
= textInfo
->staticText
.textOption();
805 m_roleEditor
->document()->setDefaultTextOption(textOption
);
807 const int textSelectionLength
= selectionLength(text
);
809 if (textSelectionLength
> 0) {
810 QTextCursor cursor
= m_roleEditor
->textCursor();
811 cursor
.movePosition(QTextCursor::StartOfBlock
);
812 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
813 m_roleEditor
->setTextCursor(cursor
);
816 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
817 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
818 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
819 this, &KStandardItemListWidget::slotRoleEditingFinished
);
821 // Adjust the geometry of the editor
822 QRectF rect
= roleEditingRect(current
);
823 const int frameWidth
= m_roleEditor
->frameWidth();
824 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
825 rect
.translate(pos());
826 if (rect
.right() > parent
->width()) {
827 rect
.setWidth(parent
->width() - rect
.left());
829 m_roleEditor
->setGeometry(rect
.toRect());
830 m_roleEditor
->show();
831 m_roleEditor
->setFocus();
834 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
836 KItemListWidget::iconSizeChanged(current
, previous
);
838 invalidateIconCache();
839 triggerCacheRefreshing();
843 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
846 setEditedRole(QByteArray());
847 Q_ASSERT(!m_roleEditor
);
850 KItemListWidget::resizeEvent(event
);
852 m_dirtyLayout
= true;
855 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
857 KItemListWidget::showEvent(event
);
859 // Listen to changes of the clipboard to mark the item as cut/uncut
860 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
862 const QUrl itemUrl
= data().value("url").toUrl();
863 m_isCut
= clipboard
->isCut(itemUrl
);
865 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
866 this, &KStandardItemListWidget::slotCutItemsChanged
);
869 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
871 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
872 this, &KStandardItemListWidget::slotCutItemsChanged
);
874 KItemListWidget::hideEvent(event
);
877 bool KStandardItemListWidget::event(QEvent
*event
)
879 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
880 || event
->type() == QEvent::PaletteChange
) {
881 m_dirtyContent
= true;
884 return KItemListWidget::event(event
);
887 void KStandardItemListWidget::finishRoleEditing()
889 if (!editedRole().isEmpty() && m_roleEditor
) {
890 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
894 void KStandardItemListWidget::slotCutItemsChanged()
896 const QUrl itemUrl
= data().value("url").toUrl();
897 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
898 if (m_isCut
!= isCut
) {
900 m_pixmap
= QPixmap();
901 m_dirtyContent
= true;
906 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
907 const QVariant
& value
)
910 Q_EMIT
roleEditingCanceled(index(), role
, value
);
911 setEditedRole(QByteArray());
914 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
915 const QVariant
& value
)
918 Q_EMIT
roleEditingFinished(index(), role
, value
);
919 setEditedRole(QByteArray());
922 void KStandardItemListWidget::triggerCacheRefreshing()
924 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
930 const QHash
<QByteArray
, QVariant
> values
= data();
931 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
932 m_isHidden
= isHidden();
933 m_customizedFont
= customizedFont(styleOption().font
);
934 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
935 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(),
936 qreal(), [this](qreal sum
, const auto &role
){ return sum
+ columnWidth(role
); });
938 updateExpansionArea();
943 m_dirtyLayout
= false;
944 m_dirtyContent
= false;
945 m_dirtyContentRoles
.clear();
948 void KStandardItemListWidget::updateExpansionArea()
950 if (m_supportsItemExpanding
) {
951 const QHash
<QByteArray
, QVariant
> values
= data();
952 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
953 if (expandedParentsCount
>= 0) {
954 const int widgetIconSize
= iconSize();
955 const qreal widgetHeight
= size().height();
956 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
957 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
959 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
960 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
965 m_expansionArea
= QRectF();
968 void KStandardItemListWidget::updatePixmapCache()
970 // Precondition: Requires already updated m_textPos values to calculate
971 // the remaining height when the alignment is vertical.
973 const QSizeF widgetSize
= size();
974 const bool iconOnTop
= (m_layout
== IconsLayout
);
975 const KItemListStyleOption
& option
= styleOption();
976 const qreal padding
= option
.padding
;
978 const int widgetIconSize
= iconSize();
979 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
980 const int maxIconHeight
= widgetIconSize
;
982 const QHash
<QByteArray
, QVariant
> values
= data();
984 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
985 if (!updatePixmap
&& m_dirtyContent
) {
986 updatePixmap
= m_dirtyContentRoles
.isEmpty()
987 || m_dirtyContentRoles
.contains("iconPixmap")
988 || m_dirtyContentRoles
.contains("iconName")
989 || m_dirtyContentRoles
.contains("iconOverlays");
993 m_pixmap
= QPixmap();
995 int sequenceIndex
= hoverSequenceIndex();
997 if (values
.contains("hoverSequencePixmaps")) {
998 // Use one of the hover sequence pixmaps instead of the default
1001 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1003 if (values
.contains("hoverSequenceWraparoundPoint")) {
1004 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1006 sequenceIndex
%= static_cast<int>(wap
);
1010 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
1012 if (loadedIndex
!= 0) {
1013 m_pixmap
= pixmaps
[loadedIndex
];
1017 if (m_pixmap
.isNull()) {
1018 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1021 if (m_pixmap
.isNull()) {
1022 // Use the icon that fits to the MIME-type
1023 QString iconName
= values
["iconName"].toString();
1024 if (iconName
.isEmpty()) {
1025 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1026 // use a generic icon as fallback
1027 iconName
= QStringLiteral("unknown");
1029 const QStringList overlays
= values
["iconOverlays"].toStringList();
1030 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1032 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1033 // A custom pixmap has been applied. Assure that the pixmap
1034 // is scaled to the maximum available size.
1035 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1038 if (m_pixmap
.isNull()) {
1039 m_hoverPixmap
= QPixmap();
1044 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1045 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1049 KIconEffect::semiTransparent(m_pixmap
);
1052 if (m_layout
== IconsLayout
&& isSelected()) {
1053 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1054 QImage image
= m_pixmap
.toImage();
1055 if (image
.isNull()) {
1056 m_hoverPixmap
= QPixmap();
1059 KIconEffect::colorize(image
, color
, 0.8f
);
1060 m_pixmap
= QPixmap::fromImage(image
);
1064 if (!m_overlay
.isNull()) {
1065 QPainter
painter(&m_pixmap
);
1066 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1069 int scaledIconSize
= 0;
1071 const TextInfo
* textInfo
= m_textInfo
.value("text");
1072 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1074 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1075 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1076 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1077 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1080 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1081 const int maxScaledIconHeight
= scaledIconSize
;
1083 m_scaledPixmapSize
= m_pixmap
.size();
1084 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1085 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1088 // Center horizontally and align on bottom within the icon-area
1089 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1090 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1092 // Center horizontally and vertically within the icon-area
1093 const TextInfo
* textInfo
= m_textInfo
.value("text");
1094 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1095 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1097 // Derive icon's vertical center from the center of the text frame, including
1098 // any necessary adjustment if the font's midline is offset from the frame center
1099 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1100 - m_customizedFontMetrics
.descent()
1101 - m_customizedFontMetrics
.capHeight() / 2.0;
1102 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1106 if (m_layout
== IconsLayout
) {
1107 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1109 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1110 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1111 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
,
1112 m_pixmapPos
.y() - 0.5 * heightOffset
);
1113 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1114 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1117 // Prepare the pixmap that is used when the item gets hovered
1119 m_hoverPixmap
= m_pixmap
;
1120 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1121 // In the KIconLoader terminology, active = hover.
1122 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1123 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1125 m_hoverPixmap
= m_pixmap
;
1127 } else if (hoverOpacity() <= 0.0) {
1128 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1129 m_hoverPixmap
= QPixmap();
1133 void KStandardItemListWidget::updateTextsCache()
1135 QTextOption textOption
;
1138 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1139 textOption
.setAlignment(Qt::AlignHCenter
);
1143 textOption
.setAlignment(Qt::AlignLeft
);
1144 textOption
.setWrapMode(QTextOption::NoWrap
);
1151 qDeleteAll(m_textInfo
);
1153 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1154 TextInfo
* textInfo
= new TextInfo();
1155 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1156 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1157 textInfo
->staticText
.setTextOption(textOption
);
1158 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1162 case IconsLayout
: updateIconsLayoutTextCache(); break;
1163 case CompactLayout
: updateCompactLayoutTextCache(); break;
1164 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1165 default: Q_ASSERT(false); break;
1168 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1169 if (ratingTextInfo
) {
1170 // The text of the rating-role has been set to empty to get
1171 // replaced by a rating-image showing the rating as stars.
1172 const KItemListStyleOption
& option
= styleOption();
1173 QSizeF ratingSize
= preferredRatingSize(option
);
1175 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1176 ? columnWidth("rating") - columnPadding(option
)
1178 if (ratingSize
.width() > availableWidth
) {
1179 ratingSize
.rwidth() = availableWidth
;
1181 const qreal dpr
= qApp
->devicePixelRatio();
1182 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1183 m_rating
.setDevicePixelRatio(dpr
);
1184 m_rating
.fill(Qt::transparent
);
1186 QPainter
painter(&m_rating
);
1187 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1188 const int rating
= data().value("rating").toInt();
1189 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1190 } else if (!m_rating
.isNull()) {
1191 m_rating
= QPixmap();
1195 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1197 const auto extensionIndex
= text
.lastIndexOf('.');
1198 if (extensionIndex
!= -1) {
1199 // has file extension
1200 const auto extensionLength
= text
.length() - extensionIndex
;
1201 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1202 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1203 // if we have room to display the file extension and the extension is not too long
1204 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1206 elidingWidth
- extensionWidth
);
1207 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1208 ret
.append(text
.rightRef(extensionLength
));
1210 ret
.append(QStringView(text
).right(extensionLength
));
1215 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1219 void KStandardItemListWidget::updateIconsLayoutTextCache()
1226 // might get wrapped above
1228 // Additional role 1
1229 // Additional role 2
1231 const QHash
<QByteArray
, QVariant
> values
= data();
1233 const KItemListStyleOption
& option
= styleOption();
1234 const qreal padding
= option
.padding
;
1235 const qreal maxWidth
= size().width() - 2 * padding
;
1236 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1238 // Initialize properties for the "text" role. It will be used as anchor
1239 // for initializing the position of the other roles.
1240 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1241 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1242 nameTextInfo
->staticText
.setText(nameText
);
1244 // Calculate the number of lines required for the name and the required width
1245 qreal nameWidth
= 0;
1246 qreal nameHeight
= 0;
1249 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1250 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1251 layout
.beginLayout();
1252 int nameLineIndex
= 0;
1253 while ((line
= layout
.createLine()).isValid()) {
1254 line
.setLineWidth(maxWidth
);
1255 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1256 nameHeight
+= line
.height();
1259 if (nameLineIndex
== option
.maxTextLines
) {
1260 // The maximum number of textlines has been reached. If this is
1261 // the case provide an elided text if necessary.
1262 const int textLength
= line
.textStart() + line
.textLength();
1263 if (textLength
< nameText
.length()) {
1264 // Elide the last line of the text
1265 qreal elidingWidth
= maxWidth
;
1266 qreal lastLineWidth
;
1268 QString lastTextLine
= nameText
.mid(line
.textStart());
1269 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1270 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1271 nameTextInfo
->staticText
.setText(elidedText
);
1273 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1275 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1276 // to avoid problems related to different width calculation code paths
1277 // within Qt. (see bug 337104)
1278 elidingWidth
-= 1.0;
1279 } while (lastLineWidth
> maxWidth
);
1281 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1288 // Use one line for each additional information
1289 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1290 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1291 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1292 nameTextInfo
->pos
.y(),
1296 // Calculate the position for each additional information
1297 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1298 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1299 if (role
== "text") {
1303 const QString text
= roleText(role
, values
);
1304 TextInfo
* textInfo
= m_textInfo
.value(role
);
1305 textInfo
->staticText
.setText(text
);
1307 qreal requiredWidth
= 0;
1309 QTextLayout
layout(text
, m_customizedFont
);
1310 QTextOption textOption
;
1311 textOption
.setWrapMode(QTextOption::NoWrap
);
1312 layout
.setTextOption(textOption
);
1314 layout
.beginLayout();
1315 QTextLine textLine
= layout
.createLine();
1316 if (textLine
.isValid()) {
1317 textLine
.setLineWidth(maxWidth
);
1318 requiredWidth
= textLine
.naturalTextWidth();
1319 if (requiredWidth
> maxWidth
) {
1320 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1321 textInfo
->staticText
.setText(elidedText
);
1322 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1323 } else if (role
== "rating") {
1324 // Use the width of the rating pixmap, because the rating text is empty.
1325 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1330 textInfo
->pos
= QPointF(padding
, y
);
1331 textInfo
->staticText
.setTextWidth(maxWidth
);
1333 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1335 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1336 if (!textRect
.isEmpty()) {
1337 m_textRect
|= textRect
;
1343 // Add a padding to the text rectangle
1344 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1347 void KStandardItemListWidget::updateCompactLayoutTextCache()
1349 // +------+ Name role
1350 // | Icon | Additional role 1
1351 // +------+ Additional role 2
1353 const QHash
<QByteArray
, QVariant
> values
= data();
1355 const KItemListStyleOption
& option
= styleOption();
1356 const qreal widgetHeight
= size().height();
1357 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1358 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1360 qreal maximumRequiredTextWidth
= 0;
1361 const qreal x
= option
.padding
* 3 + iconSize();
1362 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1363 const qreal maxWidth
= size().width() - x
- option
.padding
;
1364 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1365 const QString text
= roleText(role
, values
);
1366 TextInfo
* textInfo
= m_textInfo
.value(role
);
1367 textInfo
->staticText
.setText(text
);
1369 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1370 if (requiredWidth
> maxWidth
) {
1371 requiredWidth
= maxWidth
;
1372 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1373 textInfo
->staticText
.setText(elidedText
);
1376 textInfo
->pos
= QPointF(x
, y
);
1377 textInfo
->staticText
.setTextWidth(maxWidth
);
1379 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1384 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1387 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1389 // Precondition: Requires already updated m_expansionArea
1390 // to determine the left position.
1393 // | Icon | Name role Additional role 1 Additional role 2
1395 m_textRect
= QRectF();
1397 const KItemListStyleOption
& option
= styleOption();
1398 const QHash
<QByteArray
, QVariant
> values
= data();
1400 const qreal widgetHeight
= size().height();
1401 const int fontHeight
= m_customizedFontMetrics
.height();
1403 const qreal columnWidthInc
= columnPadding(option
);
1404 qreal firstColumnInc
= iconSize();
1405 if (m_supportsItemExpanding
) {
1406 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1408 firstColumnInc
+= option
.padding
+ sidePadding();
1411 qreal x
= firstColumnInc
;
1412 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1414 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1415 QString text
= roleText(role
, values
);
1417 // Elide the text in case it does not fit into the available column-width
1418 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1419 const qreal roleWidth
= columnWidth(role
);
1420 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1422 const bool isTextRole
= (role
== "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
1439 ? size().width() - textInfo
->pos
.x()
1440 : requiredWidth
+ 2 * option
.padding
;
1441 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1442 textWidth
, size().height());
1444 // The column after the name should always be aligned on the same x-position independent
1445 // from the expansion-level shown in the name column
1446 x
-= firstColumnInc
- sidePadding();
1447 } else if (isRoleRightAligned(role
)) {
1448 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1453 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1456 if (m_customTextColor
.isValid()) {
1457 c1
= m_customTextColor
;
1458 } else if (isSelected()) {
1459 // The detail text colour needs to match the main text (HighlightedText) for the same level
1460 // of readability. We short circuit early here to avoid interpolating with another colour.
1461 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1464 c1
= styleOption().palette
.text().color();
1467 // For the color of the additional info the inactive text color
1468 // is not used as this might lead to unreadable text for some color schemes. Instead
1469 // the text color c1 is slightly mixed with the background color.
1470 const QColor c2
= styleOption().palette
.base().color();
1472 const int p2
= 100 - p1
;
1473 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1474 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1475 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1478 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1480 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1481 QPixmap scaledPixmap
= pixmap
;
1482 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1483 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1484 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1486 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1487 painter
->setPen(Qt::blue
);
1488 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1491 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1495 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1497 const int siblingSize
= size().height();
1498 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1499 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1501 bool isItemSibling
= true;
1503 const QBitArray siblings
= siblingsInformation();
1504 QStyleOption option
;
1505 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1506 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1507 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1508 option
.rect
= siblingRect
;
1509 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1510 if (isItemSibling
) {
1511 option
.state
|= QStyle::State_Item
;
1512 if (m_isExpandable
) {
1513 option
.state
|= QStyle::State_Children
;
1515 if (data().value("isExpanded").toBool()) {
1516 option
.state
|= QStyle::State_Open
;
1518 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1519 isItemSibling
= false;
1521 option
.palette
.setColor(QPalette::Text
, normalColor
);
1524 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1526 siblingRect
.translate(-siblingRect
.width(), 0);
1530 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1532 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1537 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1538 if (m_layout
== DetailsLayout
) {
1539 rect
.setWidth(columnWidth(role
) - rect
.x());
1545 void KStandardItemListWidget::closeRoleEditor()
1547 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1548 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1549 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1550 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1552 if (m_roleEditor
->hasFocus()) {
1553 // If the editing was not ended by a FocusOut event, we have
1554 // to transfer the keyboard focus back to the KItemListContainer.
1555 scene()->views()[0]->parentWidget()->setFocus();
1558 if (m_oldRoleEditor
) {
1559 m_oldRoleEditor
->deleteLater();
1561 m_oldRoleEditor
= m_roleEditor
;
1562 m_roleEditor
->hide();
1563 m_roleEditor
= nullptr;
1566 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1568 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1570 size
*= qApp
->devicePixelRatio();
1572 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1575 if (!QPixmapCache::find(key
, &pixmap
)) {
1576 QIcon icon
= QIcon::fromTheme(name
);
1577 if (icon
.isNull()) {
1581 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1582 icon
= fallbackIcon
;
1585 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1586 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1587 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1590 // Strangely KFileItem::overlays() returns empty string-values, so
1591 // we need to check first whether an overlay must be drawn at all.
1592 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1593 // assumes that an overlay will be drawn and has some additional
1595 for (const QString
& overlay
: overlays
) {
1596 if (!overlay
.isEmpty()) {
1597 int state
= KIconLoader::DefaultState
;
1603 state
= KIconLoader::ActiveState
;
1605 case QIcon::Disabled
:
1606 state
= KIconLoader::DisabledState
;
1608 case QIcon::Selected
:
1609 state
= KIconLoader::SelectedState
;
1613 // There is at least one overlay, draw all overlays above m_pixmap
1614 // and cancel the check
1615 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1620 QPixmapCache::insert(key
, pixmap
);
1622 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1627 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1629 const qreal height
= option
.fontMetrics
.ascent();
1630 return QSizeF(height
* 5, height
);
1633 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1635 return option
.padding
* 6;