2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
41 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
42 case KStandardItemListView::IconsLayout
:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
46 case KStandardItemListView::CompactLayout
:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
50 case KStandardItemListView::DetailsLayout
:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
60 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
62 const KItemListView
* view
) const
64 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
65 const KItemListStyleOption
& option
= view
->styleOption();
67 const QString text
= roleText(role
, values
);
68 qreal width
= KStandardItemListWidget::columnPadding(option
);
70 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
71 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
73 if (role
== "rating") {
74 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
76 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
77 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
79 width
+= fontMetrics
.horizontalAdvance(text
);
82 if (view
->supportsItemExpanding()) {
83 // Increase the width by the expansion-toggle and the current expansion level
84 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
85 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
86 width
+= (expandedParentsCount
+ 1) * height
;
89 // Increase the width by the required space for the icon
90 width
+= option
.padding
* 2 + option
.iconSize
;
97 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
* view
) const
99 return view
->model()->data(index
).value("text").toString();
102 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
* view
) const
109 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
110 const QHash
<QByteArray
, QVariant
>& values
) const
112 if (role
== "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
116 return values
.value(role
).toString();
119 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
& baseFont
) const
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
126 const KItemListStyleOption
& option
= view
->styleOption();
127 const QFont
& normalFont
= option
.font
;
128 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
130 const qreal itemWidth
= view
->itemSize().width();
131 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
132 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
133 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
135 const QFont linkFont
= customizedFontForLinks(normalFont
);
137 QTextOption
textOption(Qt::AlignHCenter
);
138 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
140 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
141 if (logicalHeightHints
.at(index
).first
> 0.0) {
145 // If the current item is a link, we use the customized link font instead of the normal font.
146 const QFont
& font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
148 const QString
& text
= KStringHandler::preProcessWrap(itemText(index
, view
));
150 // Calculate the number of lines required for wrapping the name
151 qreal textHeight
= 0;
152 QTextLayout
layout(text
, font
);
153 layout
.setTextOption(textOption
);
154 layout
.beginLayout();
157 bool isElided
= false;
158 while ((line
= layout
.createLine()).isValid()) {
159 line
.setLineWidth(maxWidth
);
160 line
.naturalTextWidth();
161 textHeight
+= line
.height();
164 if (lineCount
== option
.maxTextLines
) {
165 isElided
= layout
.createLine().isValid();
171 // Add one line for each additional information
172 textHeight
+= additionalRolesSpacing
;
174 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
175 logicalHeightHints
[index
].second
= isElided
;
178 logicalWidthHint
= itemWidth
;
181 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
183 const KItemListStyleOption
& option
= view
->styleOption();
184 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
185 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
187 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
188 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
189 const qreal maxWidth
= option
.maxTextWidth
;
190 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
191 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
193 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
195 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
196 if (logicalHeightHints
.at(index
).first
> 0.0) {
200 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
201 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
203 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
204 // to show all roles without horizontal clipping.
205 qreal maximumRequiredWidth
= 0.0;
207 if (showOnlyTextRole
) {
208 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
210 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
211 for (const QByteArray
& role
: visibleRoles
) {
212 const QString
& text
= roleText(role
, values
);
213 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
214 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
218 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
219 if (maxWidth
> 0 && width
> maxWidth
) {
223 logicalHeightHints
[index
].first
= width
;
226 logicalWidthHint
= height
;
229 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
231 const KItemListStyleOption
& option
= view
->styleOption();
232 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
233 logicalHeightHints
.fill(std::make_pair(height
, false));
234 logicalWidthHint
= -1.0;
237 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
238 KItemListWidget(informant
, parent
),
243 m_customizedFontMetrics(m_customizedFont
),
244 m_isExpandable(false),
245 m_supportsItemExpanding(false),
247 m_dirtyContent(true),
248 m_dirtyContentRoles(),
249 m_layout(IconsLayout
),
252 m_scaledPixmapSize(),
257 m_sortedVisibleRoles(),
260 m_additionalInfoTextColor(),
263 m_roleEditor(nullptr),
264 m_oldRoleEditor(nullptr)
268 KStandardItemListWidget::~KStandardItemListWidget()
270 qDeleteAll(m_textInfo
);
274 m_roleEditor
->deleteLater();
277 if (m_oldRoleEditor
) {
278 m_oldRoleEditor
->deleteLater();
282 void KStandardItemListWidget::setLayout(Layout layout
)
284 if (m_layout
!= layout
) {
286 m_dirtyLayout
= true;
287 updateAdditionalInfoTextColor();
292 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
297 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
) {
298 if (m_highlightEntireRow
!= highlightEntireRow
) {
299 m_highlightEntireRow
= highlightEntireRow
;
300 m_dirtyLayout
= true;
305 bool KStandardItemListWidget::highlightEntireRow() const {
306 return m_highlightEntireRow
;
309 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
311 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
312 m_supportsItemExpanding
= supportsItemExpanding
;
313 m_dirtyLayout
= true;
318 bool KStandardItemListWidget::supportsItemExpanding() const
320 return m_supportsItemExpanding
;
323 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
325 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
327 KItemListWidget::paint(painter
, option
, widget
);
329 if (!m_expansionArea
.isEmpty()) {
330 drawSiblingsInformation(painter
);
333 const KItemListStyleOption
& itemListStyleOption
= styleOption();
334 if (isHovered() && !m_pixmap
.isNull()) {
335 if (hoverOpacity() < 1.0) {
337 * Linear interpolation between m_pixmap and m_hoverPixmap.
339 * Note that this cannot be achieved by painting m_hoverPixmap over
340 * m_pixmap, even if the opacities are adjusted. For details see
341 * https://git.reviewboard.kde.org/r/109614/
343 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
344 QPixmap
pixmap1(m_pixmap
.size());
345 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
346 pixmap1
.fill(Qt::transparent
);
348 QPainter
p(&pixmap1
);
349 p
.setOpacity(1.0 - hoverOpacity());
350 p
.drawPixmap(0, 0, m_pixmap
);
353 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
354 QPixmap
pixmap2(pixmap1
.size());
355 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
356 pixmap2
.fill(Qt::transparent
);
358 QPainter
p(&pixmap2
);
359 p
.setOpacity(hoverOpacity());
360 p
.drawPixmap(0, 0, m_hoverPixmap
);
363 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
364 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
365 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
367 QPainter
p(&pixmap1
);
368 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
369 p
.drawPixmap(0, 0, pixmap2
);
372 // Finally paint pixmap1 on the widget
373 drawPixmap(painter
, pixmap1
);
375 drawPixmap(painter
, m_hoverPixmap
);
377 } else if (!m_pixmap
.isNull()) {
378 drawPixmap(painter
, m_pixmap
);
381 painter
->setFont(m_customizedFont
);
382 painter
->setPen(textColor());
383 const TextInfo
* textInfo
= m_textInfo
.value("text");
386 // It seems that we can end up here even if m_textInfo does not contain
387 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
388 // this can only happen if the index is negative. This can happen when
389 // the item is about to be removed, see KItemListView::slotItemsRemoved().
390 // TODO: try to reproduce the crash and find a better fix.
394 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
396 bool clipAdditionalInfoBounds
= false;
397 if (m_supportsItemExpanding
) {
398 // Prevent a possible overlapping of the additional-information texts
399 // with the icon. This can happen if the user has minimized the width
400 // of the name-column to a very small value.
401 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
402 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
403 clipAdditionalInfoBounds
= true;
405 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
409 painter
->setPen(m_additionalInfoTextColor
);
410 painter
->setFont(m_customizedFont
);
412 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
413 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
414 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
417 if (!m_rating
.isNull()) {
418 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
419 QPointF pos
= ratingTextInfo
->pos
;
420 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
421 if (align
& Qt::AlignHCenter
) {
422 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
424 painter
->drawPixmap(pos
, m_rating
);
427 if (clipAdditionalInfoBounds
) {
431 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
432 painter
->setBrush(Qt::NoBrush
);
433 painter
->setPen(Qt::green
);
434 painter
->drawRect(m_iconRect
);
436 painter
->setPen(Qt::blue
);
437 painter
->drawRect(m_textRect
);
439 painter
->setPen(Qt::red
);
440 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
441 painter
->drawRect(rect());
445 QRectF
KStandardItemListWidget::iconRect() const
447 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
451 QRectF
KStandardItemListWidget::textRect() const
453 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
457 QRectF
KStandardItemListWidget::textFocusRect() const
459 // In the compact- and details-layout a larger textRect() is returned to be aligned
460 // with the iconRect(). This is useful to have a larger selection/hover-area
461 // when having a quite large icon size but only one line of text. Still the
462 // focus rectangle should be shown as narrow as possible around the text.
464 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
467 case CompactLayout
: {
468 QRectF rect
= m_textRect
;
469 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
470 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
471 rect
.setTop(topText
->pos
.y());
472 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
476 case DetailsLayout
: {
477 QRectF rect
= m_textRect
;
478 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
479 rect
.setTop(textInfo
->pos
.y());
480 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
482 const KItemListStyleOption
& option
= styleOption();
483 if (option
.extendedSelectionRegion
) {
484 const QString text
= textInfo
->staticText
.text();
485 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
498 QRectF
KStandardItemListWidget::selectionRect() const
500 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
507 case DetailsLayout
: {
508 const int padding
= styleOption().padding
;
509 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
510 QRectF result
= adjustedIconRect
| m_textRect
;
511 if (m_highlightEntireRow
) {
512 result
.setRight(m_columnWidthSum
+ leadingPadding());
525 QRectF
KStandardItemListWidget::expansionToggleRect() const
527 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
528 return m_isExpandable
? m_expansionArea
: QRectF();
531 QRectF
KStandardItemListWidget::selectionToggleRect() const
533 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
535 const int iconHeight
= styleOption().iconSize
;
537 int toggleSize
= KIconLoader::SizeSmall
;
538 if (iconHeight
>= KIconLoader::SizeEnormous
) {
539 toggleSize
= KIconLoader::SizeMedium
;
540 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
541 toggleSize
= KIconLoader::SizeSmallMedium
;
544 QPointF pos
= iconRect().topLeft();
546 // If the selection toggle has a very small distance to the
547 // widget borders, the size of the selection toggle will get
548 // increased to prevent an accidental clicking of the item
549 // when trying to hit the toggle.
550 const int widgetHeight
= size().height();
551 const int widgetWidth
= size().width();
552 const int minMargin
= 2;
554 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
555 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
556 toggleSize
= widgetHeight
;
559 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
560 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
561 toggleSize
= widgetWidth
;
565 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
568 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
571 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
572 if (m_layout
!= DetailsLayout
) {
576 // Only return the content of the text-column as pixmap
577 const int leftClip
= m_pixmapPos
.x();
579 const TextInfo
* textInfo
= m_textInfo
.value("text");
580 const int rightClip
= textInfo
->pos
.x() +
581 textInfo
->staticText
.size().width() +
582 2 * styleOption().padding
;
584 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
585 clippedPixmap
.fill(Qt::transparent
);
587 QPainter
painter(&clippedPixmap
);
588 painter
.drawPixmap(-leftClip
, 0, pixmap
);
590 return clippedPixmap
;
594 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
596 return new KStandardItemListWidgetInformant();
599 void KStandardItemListWidget::invalidateCache()
601 m_dirtyLayout
= true;
602 m_dirtyContent
= true;
605 void KStandardItemListWidget::invalidateIconCache()
607 m_dirtyContent
= true;
608 m_dirtyContentRoles
.insert("iconPixmap");
609 m_dirtyContentRoles
.insert("iconOverlays");
612 void KStandardItemListWidget::refreshCache()
616 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
622 bool KStandardItemListWidget::isHidden() const
627 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
632 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
634 return QPalette::Text
;
637 void KStandardItemListWidget::setTextColor(const QColor
& color
)
639 if (color
!= m_customTextColor
) {
640 m_customTextColor
= color
;
641 updateAdditionalInfoTextColor();
646 QColor
KStandardItemListWidget::textColor() const
650 return m_additionalInfoTextColor
;
651 } else if (m_customTextColor
.isValid()) {
652 return m_customTextColor
;
656 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
657 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
658 return styleOption().palette
.color(group
, role
);
661 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
664 m_dirtyContent
= true;
668 QPixmap
KStandardItemListWidget::overlay() const
674 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
675 const QHash
<QByteArray
, QVariant
>& values
) const
677 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
680 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
681 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
>& current
,
714 const QList
<QByteArray
>& previous
)
717 m_sortedVisibleRoles
= current
;
718 m_dirtyLayout
= true;
721 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
728 m_dirtyLayout
= true;
731 void KStandardItemListWidget::leadingPaddingChanged(qreal padding
) {
733 m_dirtyLayout
= true;
736 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
737 const KItemListStyleOption
& previous
)
741 updateAdditionalInfoTextColor();
742 m_dirtyLayout
= true;
745 void KStandardItemListWidget::hoveredChanged(bool hovered
)
748 m_dirtyLayout
= true;
751 void KStandardItemListWidget::selectedChanged(bool selected
)
754 updateAdditionalInfoTextColor();
755 m_dirtyContent
= true;
758 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
762 m_dirtyLayout
= true;
765 int KStandardItemListWidget::selectionLength(const QString
& text
) const
767 return text
.length();
770 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
774 QGraphicsView
* parent
= scene()->views()[0];
775 if (current
.isEmpty() || !parent
|| current
!= "text") {
777 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
779 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
780 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
781 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
782 this, &KStandardItemListWidget::slotRoleEditingFinished
);
784 if (m_oldRoleEditor
) {
785 m_oldRoleEditor
->deleteLater();
787 m_oldRoleEditor
= m_roleEditor
;
788 m_roleEditor
->hide();
789 m_roleEditor
= nullptr;
794 Q_ASSERT(!m_roleEditor
);
796 const TextInfo
* textInfo
= m_textInfo
.value("text");
798 m_roleEditor
= new KItemListRoleEditor(parent
);
799 m_roleEditor
->setRole(current
);
800 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
801 m_roleEditor
->setFont(styleOption().font
);
803 const QString text
= data().value(current
).toString();
804 m_roleEditor
->setPlainText(text
);
806 QTextOption textOption
= textInfo
->staticText
.textOption();
807 m_roleEditor
->document()->setDefaultTextOption(textOption
);
809 const int textSelectionLength
= selectionLength(text
);
811 if (textSelectionLength
> 0) {
812 QTextCursor cursor
= m_roleEditor
->textCursor();
813 cursor
.movePosition(QTextCursor::StartOfBlock
);
814 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
815 m_roleEditor
->setTextCursor(cursor
);
818 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
819 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
820 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
821 this, &KStandardItemListWidget::slotRoleEditingFinished
);
823 // Adjust the geometry of the editor
824 QRectF rect
= roleEditingRect(current
);
825 const int frameWidth
= m_roleEditor
->frameWidth();
826 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
827 rect
.translate(pos());
828 if (rect
.right() > parent
->width()) {
829 rect
.setWidth(parent
->width() - rect
.left());
831 m_roleEditor
->setGeometry(rect
.toRect());
832 m_roleEditor
->show();
833 m_roleEditor
->setFocus();
836 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
839 setEditedRole(QByteArray());
840 Q_ASSERT(!m_roleEditor
);
843 KItemListWidget::resizeEvent(event
);
845 m_dirtyLayout
= true;
848 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
850 KItemListWidget::showEvent(event
);
852 // Listen to changes of the clipboard to mark the item as cut/uncut
853 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
855 const QUrl itemUrl
= data().value("url").toUrl();
856 m_isCut
= clipboard
->isCut(itemUrl
);
858 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
859 this, &KStandardItemListWidget::slotCutItemsChanged
);
862 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
864 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
865 this, &KStandardItemListWidget::slotCutItemsChanged
);
867 KItemListWidget::hideEvent(event
);
870 bool KStandardItemListWidget::event(QEvent
*event
)
872 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
873 || 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
,
900 const QVariant
& value
)
903 Q_EMIT
roleEditingCanceled(index(), role
, value
);
904 setEditedRole(QByteArray());
907 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
908 const QVariant
& value
)
911 Q_EMIT
roleEditingFinished(index(), role
, value
);
912 setEditedRole(QByteArray());
915 void KStandardItemListWidget::triggerCacheRefreshing()
917 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
923 const QHash
<QByteArray
, QVariant
> values
= data();
924 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
925 m_isHidden
= isHidden();
926 m_customizedFont
= customizedFont(styleOption().font
);
927 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
928 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(),
929 qreal(), [this](qreal sum
, const auto &role
){ return sum
+ columnWidth(role
); });
931 updateExpansionArea();
936 m_dirtyLayout
= false;
937 m_dirtyContent
= false;
938 m_dirtyContentRoles
.clear();
941 void KStandardItemListWidget::updateExpansionArea()
943 if (m_supportsItemExpanding
) {
944 const QHash
<QByteArray
, QVariant
> values
= data();
945 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
946 if (expandedParentsCount
>= 0) {
947 const KItemListStyleOption
& option
= styleOption();
948 const qreal widgetHeight
= size().height();
949 const qreal inc
= (widgetHeight
- option
.iconSize
) / 2;
950 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
952 const qreal xPadding
= m_highlightEntireRow
? leadingPadding() : 0;
953 m_expansionArea
= QRectF(xPadding
+ x
, y
, option
.iconSize
, option
.iconSize
);
958 m_expansionArea
= QRectF();
961 void KStandardItemListWidget::updatePixmapCache()
963 // Precondition: Requires already updated m_textPos values to calculate
964 // the remaining height when the alignment is vertical.
966 const QSizeF widgetSize
= size();
967 const bool iconOnTop
= (m_layout
== IconsLayout
);
968 const KItemListStyleOption
& option
= styleOption();
969 const qreal padding
= option
.padding
;
971 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
972 const int maxIconHeight
= option
.iconSize
;
974 const QHash
<QByteArray
, QVariant
> values
= data();
976 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
977 if (!updatePixmap
&& m_dirtyContent
) {
978 updatePixmap
= m_dirtyContentRoles
.isEmpty()
979 || m_dirtyContentRoles
.contains("iconPixmap")
980 || m_dirtyContentRoles
.contains("iconName")
981 || m_dirtyContentRoles
.contains("iconOverlays");
985 m_pixmap
= QPixmap();
987 int sequenceIndex
= hoverSequenceIndex();
989 if (values
.contains("hoverSequencePixmaps")) {
990 // Use one of the hover sequence pixmaps instead of the default
993 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
995 if (values
.contains("hoverSequenceWraparoundPoint")) {
996 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
998 sequenceIndex
%= static_cast<int>(wap
);
1002 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
1004 if (loadedIndex
!= 0) {
1005 m_pixmap
= pixmaps
[loadedIndex
];
1009 if (m_pixmap
.isNull()) {
1010 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1013 if (m_pixmap
.isNull()) {
1014 // Use the icon that fits to the MIME-type
1015 QString iconName
= values
["iconName"].toString();
1016 if (iconName
.isEmpty()) {
1017 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1018 // use a generic icon as fallback
1019 iconName
= QStringLiteral("unknown");
1021 const QStringList overlays
= values
["iconOverlays"].toStringList();
1022 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1024 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1025 // A custom pixmap has been applied. Assure that the pixmap
1026 // is scaled to the maximum available size.
1027 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1030 if (m_pixmap
.isNull()) {
1031 m_hoverPixmap
= QPixmap();
1036 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1037 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1041 KIconEffect::semiTransparent(m_pixmap
);
1044 if (m_layout
== IconsLayout
&& isSelected()) {
1045 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1046 QImage image
= m_pixmap
.toImage();
1047 if (image
.isNull()) {
1048 m_hoverPixmap
= QPixmap();
1051 KIconEffect::colorize(image
, color
, 0.8f
);
1052 m_pixmap
= QPixmap::fromImage(image
);
1056 if (!m_overlay
.isNull()) {
1057 QPainter
painter(&m_pixmap
);
1058 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1061 int scaledIconSize
= 0;
1063 const TextInfo
* textInfo
= m_textInfo
.value("text");
1064 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1066 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1067 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1068 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1069 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1072 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1073 const int maxScaledIconHeight
= scaledIconSize
;
1075 m_scaledPixmapSize
= m_pixmap
.size();
1076 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1077 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1080 // Center horizontally and align on bottom within the icon-area
1081 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1082 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1084 // Center horizontally and vertically within the icon-area
1085 const TextInfo
* textInfo
= m_textInfo
.value("text");
1086 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1087 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1089 // Derive icon's vertical center from the center of the text frame, including
1090 // any necessary adjustment if the font's midline is offset from the frame center
1091 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1092 - m_customizedFontMetrics
.descent()
1093 - m_customizedFontMetrics
.capHeight() / 2.0;
1094 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1098 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1100 // Prepare the pixmap that is used when the item gets hovered
1102 m_hoverPixmap
= m_pixmap
;
1103 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1104 // In the KIconLoader terminology, active = hover.
1105 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1106 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1108 m_hoverPixmap
= m_pixmap
;
1110 } else if (hoverOpacity() <= 0.0) {
1111 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1112 m_hoverPixmap
= QPixmap();
1116 void KStandardItemListWidget::updateTextsCache()
1118 QTextOption textOption
;
1121 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1122 textOption
.setAlignment(Qt::AlignHCenter
);
1126 textOption
.setAlignment(Qt::AlignLeft
);
1127 textOption
.setWrapMode(QTextOption::NoWrap
);
1134 qDeleteAll(m_textInfo
);
1136 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1137 TextInfo
* textInfo
= new TextInfo();
1138 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1139 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1140 textInfo
->staticText
.setTextOption(textOption
);
1141 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1145 case IconsLayout
: updateIconsLayoutTextCache(); break;
1146 case CompactLayout
: updateCompactLayoutTextCache(); break;
1147 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1148 default: Q_ASSERT(false); break;
1151 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1152 if (ratingTextInfo
) {
1153 // The text of the rating-role has been set to empty to get
1154 // replaced by a rating-image showing the rating as stars.
1155 const KItemListStyleOption
& option
= styleOption();
1156 QSizeF ratingSize
= preferredRatingSize(option
);
1158 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1159 ? columnWidth("rating") - columnPadding(option
)
1161 if (ratingSize
.width() > availableWidth
) {
1162 ratingSize
.rwidth() = availableWidth
;
1164 const qreal dpr
= qApp
->devicePixelRatio();
1165 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1166 m_rating
.setDevicePixelRatio(dpr
);
1167 m_rating
.fill(Qt::transparent
);
1169 QPainter
painter(&m_rating
);
1170 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1171 const int rating
= data().value("rating").toInt();
1172 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1173 } else if (!m_rating
.isNull()) {
1174 m_rating
= QPixmap();
1178 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1180 const auto extensionIndex
= text
.lastIndexOf('.');
1181 if (extensionIndex
!= -1) {
1182 // has file extension
1183 const auto extensionLength
= text
.length() - extensionIndex
;
1184 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1185 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1186 // if we have room to display the file extension and the extension is not too long
1187 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1189 elidingWidth
- extensionWidth
);
1190 ret
.append(text
.rightRef(extensionLength
));
1194 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1198 void KStandardItemListWidget::updateIconsLayoutTextCache()
1205 // might get wrapped above
1207 // Additional role 1
1208 // Additional role 2
1210 const QHash
<QByteArray
, QVariant
> values
= data();
1212 const KItemListStyleOption
& option
= styleOption();
1213 const qreal padding
= option
.padding
;
1214 const qreal maxWidth
= size().width() - 2 * padding
;
1215 const qreal widgetHeight
= size().height();
1216 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1218 // Initialize properties for the "text" role. It will be used as anchor
1219 // for initializing the position of the other roles.
1220 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1221 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1222 nameTextInfo
->staticText
.setText(nameText
);
1224 // Calculate the number of lines required for the name and the required width
1225 qreal nameWidth
= 0;
1226 qreal nameHeight
= 0;
1229 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1230 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1231 layout
.beginLayout();
1232 int nameLineIndex
= 0;
1233 while ((line
= layout
.createLine()).isValid()) {
1234 line
.setLineWidth(maxWidth
);
1235 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1236 nameHeight
+= line
.height();
1239 if (nameLineIndex
== option
.maxTextLines
) {
1240 // The maximum number of textlines has been reached. If this is
1241 // the case provide an elided text if necessary.
1242 const int textLength
= line
.textStart() + line
.textLength();
1243 if (textLength
< nameText
.length()) {
1244 // Elide the last line of the text
1245 qreal elidingWidth
= maxWidth
;
1246 qreal lastLineWidth
;
1248 QString lastTextLine
= nameText
.mid(line
.textStart());
1249 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1250 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1251 nameTextInfo
->staticText
.setText(elidedText
);
1253 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1255 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1256 // to avoid problems related to different width calculation code paths
1257 // within Qt. (see bug 337104)
1258 elidingWidth
-= 1.0;
1259 } while (lastLineWidth
> maxWidth
);
1261 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1268 // Use one line for each additional information
1269 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1270 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1271 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1273 additionalRolesCount
* lineSpacing
-
1275 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1276 nameTextInfo
->pos
.y(),
1280 // Calculate the position for each additional information
1281 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1282 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1283 if (role
== "text") {
1287 const QString text
= roleText(role
, values
);
1288 TextInfo
* textInfo
= m_textInfo
.value(role
);
1289 textInfo
->staticText
.setText(text
);
1291 qreal requiredWidth
= 0;
1293 QTextLayout
layout(text
, m_customizedFont
);
1294 QTextOption textOption
;
1295 textOption
.setWrapMode(QTextOption::NoWrap
);
1296 layout
.setTextOption(textOption
);
1298 layout
.beginLayout();
1299 QTextLine textLine
= layout
.createLine();
1300 if (textLine
.isValid()) {
1301 textLine
.setLineWidth(maxWidth
);
1302 requiredWidth
= textLine
.naturalTextWidth();
1303 if (requiredWidth
> maxWidth
) {
1304 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1305 textInfo
->staticText
.setText(elidedText
);
1306 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1307 } else if (role
== "rating") {
1308 // Use the width of the rating pixmap, because the rating text is empty.
1309 requiredWidth
= m_rating
.width();
1314 textInfo
->pos
= QPointF(padding
, y
);
1315 textInfo
->staticText
.setTextWidth(maxWidth
);
1317 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1318 m_textRect
|= textRect
;
1323 // Add a padding to the text rectangle
1324 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1327 void KStandardItemListWidget::updateCompactLayoutTextCache()
1329 // +------+ Name role
1330 // | Icon | Additional role 1
1331 // +------+ Additional role 2
1333 const QHash
<QByteArray
, QVariant
> values
= data();
1335 const KItemListStyleOption
& option
= styleOption();
1336 const qreal widgetHeight
= size().height();
1337 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1338 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1339 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1341 qreal maximumRequiredTextWidth
= 0;
1342 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1343 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1344 const qreal maxWidth
= size().width() - x
- option
.padding
;
1345 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1346 const QString text
= roleText(role
, values
);
1347 TextInfo
* textInfo
= m_textInfo
.value(role
);
1348 textInfo
->staticText
.setText(text
);
1350 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1351 if (requiredWidth
> maxWidth
) {
1352 requiredWidth
= maxWidth
;
1353 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1354 textInfo
->staticText
.setText(elidedText
);
1357 textInfo
->pos
= QPointF(x
, y
);
1358 textInfo
->staticText
.setTextWidth(maxWidth
);
1360 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1365 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1368 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1370 // Precondition: Requires already updated m_expansionArea
1371 // to determine the left position.
1374 // | Icon | Name role Additional role 1 Additional role 2
1376 m_textRect
= QRectF();
1378 const KItemListStyleOption
& option
= styleOption();
1379 const QHash
<QByteArray
, QVariant
> values
= data();
1381 const qreal widgetHeight
= size().height();
1382 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1383 const int fontHeight
= m_customizedFontMetrics
.height();
1385 const qreal columnWidthInc
= columnPadding(option
);
1386 qreal firstColumnInc
= scaledIconSize
;
1387 if (m_supportsItemExpanding
) {
1388 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1390 firstColumnInc
+= option
.padding
+ leadingPadding();
1393 qreal x
= firstColumnInc
;
1394 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1396 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1397 QString text
= roleText(role
, values
);
1399 // Elide the text in case it does not fit into the available column-width
1400 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1401 const qreal roleWidth
= columnWidth(role
);
1402 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1404 const bool isTextRole
= (role
== "text");
1406 availableTextWidth
-= firstColumnInc
- leadingPadding();
1409 if (requiredWidth
> availableTextWidth
) {
1410 text
= elideRightKeepExtension(text
, availableTextWidth
);
1411 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1414 TextInfo
* textInfo
= m_textInfo
.value(role
);
1415 textInfo
->staticText
.setText(text
);
1416 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1420 const qreal textWidth
= option
.extendedSelectionRegion
1421 ? size().width() - textInfo
->pos
.x()
1422 : requiredWidth
+ 2 * option
.padding
;
1423 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1424 textWidth
, size().height());
1426 // The column after the name should always be aligned on the same x-position independent
1427 // from the expansion-level shown in the name column
1428 x
-= firstColumnInc
- leadingPadding();
1429 } else if (isRoleRightAligned(role
)) {
1430 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1435 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1438 if (m_customTextColor
.isValid()) {
1439 c1
= m_customTextColor
;
1440 } else if (isSelected()) {
1441 // The detail text colour needs to match the main text (HighlightedText) for the same level
1442 // of readability. We short circuit early here to avoid interpolating with another colour.
1443 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1446 c1
= styleOption().palette
.text().color();
1449 // For the color of the additional info the inactive text color
1450 // is not used as this might lead to unreadable text for some color schemes. Instead
1451 // the text color c1 is slightly mixed with the background color.
1452 const QColor c2
= styleOption().palette
.base().color();
1454 const int p2
= 100 - p1
;
1455 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1456 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1457 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1460 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1462 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1463 QPixmap scaledPixmap
= pixmap
;
1464 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1465 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1466 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1468 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1469 painter
->setPen(Qt::blue
);
1470 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1473 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1477 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1479 const int siblingSize
= size().height();
1480 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1481 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1483 bool isItemSibling
= true;
1485 const QBitArray siblings
= siblingsInformation();
1486 QStyleOption option
;
1487 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1488 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1489 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1490 option
.rect
= siblingRect
;
1491 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1492 if (isItemSibling
) {
1493 option
.state
|= QStyle::State_Item
;
1494 if (m_isExpandable
) {
1495 option
.state
|= QStyle::State_Children
;
1497 if (data().value("isExpanded").toBool()) {
1498 option
.state
|= QStyle::State_Open
;
1500 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1501 isItemSibling
= false;
1503 option
.palette
.setColor(QPalette::Text
, normalColor
);
1506 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1508 siblingRect
.translate(-siblingRect
.width(), 0);
1512 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1514 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1519 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1520 if (m_layout
== DetailsLayout
) {
1521 rect
.setWidth(columnWidth(role
) - rect
.x());
1527 void KStandardItemListWidget::closeRoleEditor()
1529 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1530 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1531 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1532 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1534 if (m_roleEditor
->hasFocus()) {
1535 // If the editing was not ended by a FocusOut event, we have
1536 // to transfer the keyboard focus back to the KItemListContainer.
1537 scene()->views()[0]->parentWidget()->setFocus();
1540 if (m_oldRoleEditor
) {
1541 m_oldRoleEditor
->deleteLater();
1543 m_oldRoleEditor
= m_roleEditor
;
1544 m_roleEditor
->hide();
1545 m_roleEditor
= nullptr;
1548 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1550 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1552 size
*= qApp
->devicePixelRatio();
1554 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1557 if (!QPixmapCache::find(key
, &pixmap
)) {
1558 QIcon icon
= QIcon::fromTheme(name
);
1559 if (icon
.isNull()) {
1563 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1564 icon
= fallbackIcon
;
1567 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1568 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1569 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1572 // Strangely KFileItem::overlays() returns empty string-values, so
1573 // we need to check first whether an overlay must be drawn at all.
1574 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1575 // assumes that an overlay will be drawn and has some additional
1577 for (const QString
& overlay
: overlays
) {
1578 if (!overlay
.isEmpty()) {
1579 int state
= KIconLoader::DefaultState
;
1585 state
= KIconLoader::ActiveState
;
1587 case QIcon::Disabled
:
1588 state
= KIconLoader::DisabledState
;
1590 case QIcon::Selected
:
1591 state
= KIconLoader::SelectedState
;
1595 // There is at least one overlay, draw all overlays above m_pixmap
1596 // and cancel the check
1597 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1602 QPixmapCache::insert(key
, pixmap
);
1604 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1609 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1611 const qreal height
= option
.fontMetrics
.ascent();
1612 return QSizeF(height
* 5, height
);
1615 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1617 return option
.padding
* 6;