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
<qreal
>& 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
<qreal
>& 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
) > 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 while ((line
= layout
.createLine()).isValid()) {
158 line
.setLineWidth(maxWidth
);
159 line
.naturalTextWidth();
160 textHeight
+= line
.height();
163 if (lineCount
== option
.maxTextLines
) {
169 // Add one line for each additional information
170 textHeight
+= additionalRolesSpacing
;
172 logicalHeightHints
[index
] = textHeight
+ spacingAndIconHeight
;
175 logicalWidthHint
= itemWidth
;
178 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
180 const KItemListStyleOption
& option
= view
->styleOption();
181 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
182 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
184 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
185 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
186 const qreal maxWidth
= option
.maxTextWidth
;
187 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
188 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
190 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
192 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
193 if (logicalHeightHints
.at(index
) > 0.0) {
197 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
198 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
200 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
201 // to show all roles without horizontal clipping.
202 qreal maximumRequiredWidth
= 0.0;
204 if (showOnlyTextRole
) {
205 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
207 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
208 for (const QByteArray
& role
: visibleRoles
) {
209 const QString
& text
= roleText(role
, values
);
210 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
211 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
215 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
216 if (maxWidth
> 0 && width
> maxWidth
) {
220 logicalHeightHints
[index
] = width
;
223 logicalWidthHint
= height
;
226 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
228 const KItemListStyleOption
& option
= view
->styleOption();
231 if (option
.iconSize
>= KIconLoader::SizeEnormous
) {
233 } else if (option
.iconSize
>= KIconLoader::SizeHuge
) {
235 } else if (option
.iconSize
>= KIconLoader::SizeLarge
) {
237 } else if (option
.iconSize
>= KIconLoader::SizeMedium
) {
239 } else if (option
.iconSize
>= KIconLoader::SizeSmallMedium
) {
243 const qreal contentHeight
= qMax
<qreal
>(option
.iconSize
, zoomLevel
* option
.fontMetrics
.height());
244 logicalHeightHints
.fill(contentHeight
+ 2 * option
.padding
);
245 logicalWidthHint
= -1.0;
248 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
249 KItemListWidget(informant
, parent
),
254 m_customizedFontMetrics(m_customizedFont
),
255 m_isExpandable(false),
256 m_supportsItemExpanding(false),
258 m_dirtyContent(true),
259 m_dirtyContentRoles(),
260 m_layout(IconsLayout
),
263 m_scaledPixmapSize(),
267 m_sortedVisibleRoles(),
270 m_additionalInfoTextColor(),
273 m_roleEditor(nullptr),
274 m_oldRoleEditor(nullptr)
278 KStandardItemListWidget::~KStandardItemListWidget()
280 qDeleteAll(m_textInfo
);
284 m_roleEditor
->deleteLater();
287 if (m_oldRoleEditor
) {
288 m_oldRoleEditor
->deleteLater();
292 void KStandardItemListWidget::setLayout(Layout layout
)
294 if (m_layout
!= layout
) {
296 m_dirtyLayout
= true;
297 updateAdditionalInfoTextColor();
302 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
307 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
309 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
310 m_supportsItemExpanding
= supportsItemExpanding
;
311 m_dirtyLayout
= true;
316 bool KStandardItemListWidget::supportsItemExpanding() const
318 return m_supportsItemExpanding
;
321 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
323 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
325 KItemListWidget::paint(painter
, option
, widget
);
327 if (!m_expansionArea
.isEmpty()) {
328 drawSiblingsInformation(painter
);
331 const KItemListStyleOption
& itemListStyleOption
= styleOption();
332 if (isHovered() && !m_pixmap
.isNull()) {
333 if (hoverOpacity() < 1.0) {
335 * Linear interpolation between m_pixmap and m_hoverPixmap.
337 * Note that this cannot be achieved by painting m_hoverPixmap over
338 * m_pixmap, even if the opacities are adjusted. For details see
339 * https://git.reviewboard.kde.org/r/109614/
341 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
342 QPixmap
pixmap1(m_pixmap
.size());
343 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
344 pixmap1
.fill(Qt::transparent
);
346 QPainter
p(&pixmap1
);
347 p
.setOpacity(1.0 - hoverOpacity());
348 p
.drawPixmap(0, 0, m_pixmap
);
351 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
352 QPixmap
pixmap2(pixmap1
.size());
353 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
354 pixmap2
.fill(Qt::transparent
);
356 QPainter
p(&pixmap2
);
357 p
.setOpacity(hoverOpacity());
358 p
.drawPixmap(0, 0, m_hoverPixmap
);
361 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
362 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
363 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
365 QPainter
p(&pixmap1
);
366 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
367 p
.drawPixmap(0, 0, pixmap2
);
370 // Finally paint pixmap1 on the widget
371 drawPixmap(painter
, pixmap1
);
373 drawPixmap(painter
, m_hoverPixmap
);
375 } else if (!m_pixmap
.isNull()) {
376 drawPixmap(painter
, m_pixmap
);
379 painter
->setFont(m_customizedFont
);
380 painter
->setPen(textColor());
381 const TextInfo
* textInfo
= m_textInfo
.value("text");
384 // It seems that we can end up here even if m_textInfo does not contain
385 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
386 // this can only happen if the index is negative. This can happen when
387 // the item is about to be removed, see KItemListView::slotItemsRemoved().
388 // TODO: try to reproduce the crash and find a better fix.
392 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
394 bool clipAdditionalInfoBounds
= false;
395 if (m_supportsItemExpanding
) {
396 // Prevent a possible overlapping of the additional-information texts
397 // with the icon. This can happen if the user has minimized the width
398 // of the name-column to a very small value.
399 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
400 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
401 clipAdditionalInfoBounds
= true;
403 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
407 painter
->setPen(m_additionalInfoTextColor
);
408 painter
->setFont(m_customizedFont
);
410 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
411 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
412 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
415 if (!m_rating
.isNull()) {
416 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
417 QPointF pos
= ratingTextInfo
->pos
;
418 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
419 if (align
& Qt::AlignHCenter
) {
420 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
422 painter
->drawPixmap(pos
, m_rating
);
425 if (clipAdditionalInfoBounds
) {
429 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
430 painter
->setBrush(Qt::NoBrush
);
431 painter
->setPen(Qt::green
);
432 painter
->drawRect(m_iconRect
);
434 painter
->setPen(Qt::blue
);
435 painter
->drawRect(m_textRect
);
437 painter
->setPen(Qt::red
);
438 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
439 painter
->drawRect(rect());
443 QRectF
KStandardItemListWidget::iconRect() const
445 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
449 QRectF
KStandardItemListWidget::textRect() const
451 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
455 QRectF
KStandardItemListWidget::textFocusRect() const
457 // In the compact- and details-layout a larger textRect() is returned to be aligned
458 // with the iconRect(). This is useful to have a larger selection/hover-area
459 // when having a quite large icon size but only one line of text. Still the
460 // focus rectangle should be shown as narrow as possible around the text.
462 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
465 case CompactLayout
: {
466 QRectF rect
= m_textRect
;
467 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
468 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
469 rect
.setTop(topText
->pos
.y());
470 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
474 case DetailsLayout
: {
475 QRectF rect
= m_textRect
;
476 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
477 rect
.setTop(textInfo
->pos
.y());
478 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
480 const KItemListStyleOption
& option
= styleOption();
481 if (option
.extendedSelectionRegion
) {
482 const QString text
= textInfo
->staticText
.text();
483 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
496 QRectF
KStandardItemListWidget::selectionRect() const
498 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
505 case DetailsLayout
: {
506 const int padding
= styleOption().padding
;
507 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
508 return adjustedIconRect
| m_textRect
;
519 QRectF
KStandardItemListWidget::expansionToggleRect() const
521 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
522 return m_isExpandable
? m_expansionArea
: QRectF();
525 QRectF
KStandardItemListWidget::selectionToggleRect() const
527 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
529 const int iconHeight
= styleOption().iconSize
;
531 int toggleSize
= KIconLoader::SizeSmall
;
532 if (iconHeight
>= KIconLoader::SizeEnormous
) {
533 toggleSize
= KIconLoader::SizeMedium
;
534 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
535 toggleSize
= KIconLoader::SizeSmallMedium
;
538 QPointF pos
= iconRect().topLeft();
540 // If the selection toggle has a very small distance to the
541 // widget borders, the size of the selection toggle will get
542 // increased to prevent an accidental clicking of the item
543 // when trying to hit the toggle.
544 const int widgetHeight
= size().height();
545 const int widgetWidth
= size().width();
546 const int minMargin
= 2;
548 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
549 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
550 toggleSize
= widgetHeight
;
553 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
554 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
555 toggleSize
= widgetWidth
;
559 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
562 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
565 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
566 if (m_layout
!= DetailsLayout
) {
570 // Only return the content of the text-column as pixmap
571 const int leftClip
= m_pixmapPos
.x();
573 const TextInfo
* textInfo
= m_textInfo
.value("text");
574 const int rightClip
= textInfo
->pos
.x() +
575 textInfo
->staticText
.size().width() +
576 2 * styleOption().padding
;
578 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
579 clippedPixmap
.fill(Qt::transparent
);
581 QPainter
painter(&clippedPixmap
);
582 painter
.drawPixmap(-leftClip
, 0, pixmap
);
584 return clippedPixmap
;
588 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
590 return new KStandardItemListWidgetInformant();
593 void KStandardItemListWidget::invalidateCache()
595 m_dirtyLayout
= true;
596 m_dirtyContent
= true;
599 void KStandardItemListWidget::invalidateIconCache()
601 m_dirtyContent
= true;
602 m_dirtyContentRoles
.insert("iconPixmap");
603 m_dirtyContentRoles
.insert("iconOverlays");
606 void KStandardItemListWidget::refreshCache()
610 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
616 bool KStandardItemListWidget::isHidden() const
621 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
626 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
628 return QPalette::Text
;
631 void KStandardItemListWidget::setTextColor(const QColor
& color
)
633 if (color
!= m_customTextColor
) {
634 m_customTextColor
= color
;
635 updateAdditionalInfoTextColor();
640 QColor
KStandardItemListWidget::textColor() const
644 return m_additionalInfoTextColor
;
645 } else if (m_customTextColor
.isValid()) {
646 return m_customTextColor
;
650 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
651 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
652 return styleOption().palette
.color(group
, role
);
655 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
658 m_dirtyContent
= true;
662 QPixmap
KStandardItemListWidget::overlay() const
668 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
669 const QHash
<QByteArray
, QVariant
>& values
) const
671 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
674 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
675 const QSet
<QByteArray
>& roles
)
679 m_dirtyContent
= true;
681 QSet
<QByteArray
> dirtyRoles
;
682 if (roles
.isEmpty()) {
683 const auto visibleRoles
= this->visibleRoles();
684 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
689 // The URL might have changed (i.e., if the sort order of the items has
690 // been changed). Therefore, the "is cut" state must be updated.
691 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
692 const QUrl itemUrl
= data().value("url").toUrl();
693 m_isCut
= clipboard
->isCut(itemUrl
);
695 // The icon-state might depend from other roles and hence is
696 // marked as dirty whenever a role has been changed
697 dirtyRoles
.insert("iconPixmap");
698 dirtyRoles
.insert("iconName");
700 QSetIterator
<QByteArray
> it(dirtyRoles
);
701 while (it
.hasNext()) {
702 const QByteArray
& role
= it
.next();
703 m_dirtyContentRoles
.insert(role
);
707 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
708 const QList
<QByteArray
>& previous
)
711 m_sortedVisibleRoles
= current
;
712 m_dirtyLayout
= true;
715 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
722 m_dirtyLayout
= true;
725 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
726 const KItemListStyleOption
& previous
)
730 updateAdditionalInfoTextColor();
731 m_dirtyLayout
= true;
734 void KStandardItemListWidget::hoveredChanged(bool hovered
)
737 m_dirtyLayout
= true;
740 void KStandardItemListWidget::selectedChanged(bool selected
)
743 updateAdditionalInfoTextColor();
744 m_dirtyContent
= true;
747 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
751 m_dirtyLayout
= true;
754 int KStandardItemListWidget::selectionLength(const QString
& text
) const
756 return text
.length();
759 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
763 QGraphicsView
* parent
= scene()->views()[0];
764 if (current
.isEmpty() || !parent
|| current
!= "text") {
766 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
768 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
769 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
770 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
771 this, &KStandardItemListWidget::slotRoleEditingFinished
);
773 if (m_oldRoleEditor
) {
774 m_oldRoleEditor
->deleteLater();
776 m_oldRoleEditor
= m_roleEditor
;
777 m_roleEditor
->hide();
778 m_roleEditor
= nullptr;
783 Q_ASSERT(!m_roleEditor
);
785 const TextInfo
* textInfo
= m_textInfo
.value("text");
787 m_roleEditor
= new KItemListRoleEditor(parent
);
788 m_roleEditor
->setRole(current
);
789 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
790 m_roleEditor
->setFont(styleOption().font
);
792 const QString text
= data().value(current
).toString();
793 m_roleEditor
->setPlainText(text
);
795 QTextOption textOption
= textInfo
->staticText
.textOption();
796 m_roleEditor
->document()->setDefaultTextOption(textOption
);
798 const int textSelectionLength
= selectionLength(text
);
800 if (textSelectionLength
> 0) {
801 QTextCursor cursor
= m_roleEditor
->textCursor();
802 cursor
.movePosition(QTextCursor::StartOfBlock
);
803 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
804 m_roleEditor
->setTextCursor(cursor
);
807 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
808 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
809 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
810 this, &KStandardItemListWidget::slotRoleEditingFinished
);
812 // Adjust the geometry of the editor
813 QRectF rect
= roleEditingRect(current
);
814 const int frameWidth
= m_roleEditor
->frameWidth();
815 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
816 rect
.translate(pos());
817 if (rect
.right() > parent
->width()) {
818 rect
.setWidth(parent
->width() - rect
.left());
820 m_roleEditor
->setGeometry(rect
.toRect());
821 m_roleEditor
->show();
822 m_roleEditor
->setFocus();
825 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
828 setEditedRole(QByteArray());
829 Q_ASSERT(!m_roleEditor
);
832 KItemListWidget::resizeEvent(event
);
834 m_dirtyLayout
= true;
837 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
839 KItemListWidget::showEvent(event
);
841 // Listen to changes of the clipboard to mark the item as cut/uncut
842 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
844 const QUrl itemUrl
= data().value("url").toUrl();
845 m_isCut
= clipboard
->isCut(itemUrl
);
847 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
848 this, &KStandardItemListWidget::slotCutItemsChanged
);
851 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
853 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
854 this, &KStandardItemListWidget::slotCutItemsChanged
);
856 KItemListWidget::hideEvent(event
);
859 bool KStandardItemListWidget::event(QEvent
*event
)
861 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
862 || event
->type() == QEvent::PaletteChange
) {
863 m_dirtyContent
= true;
866 return KItemListWidget::event(event
);
869 void KStandardItemListWidget::finishRoleEditing()
871 if (!editedRole().isEmpty() && m_roleEditor
) {
872 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
876 void KStandardItemListWidget::slotCutItemsChanged()
878 const QUrl itemUrl
= data().value("url").toUrl();
879 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
880 if (m_isCut
!= isCut
) {
882 m_pixmap
= QPixmap();
883 m_dirtyContent
= true;
888 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
889 const QVariant
& value
)
892 Q_EMIT
roleEditingCanceled(index(), role
, value
);
893 setEditedRole(QByteArray());
896 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
897 const QVariant
& value
)
900 Q_EMIT
roleEditingFinished(index(), role
, value
);
901 setEditedRole(QByteArray());
904 void KStandardItemListWidget::triggerCacheRefreshing()
906 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
912 const QHash
<QByteArray
, QVariant
> values
= data();
913 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
914 m_isHidden
= isHidden();
915 m_customizedFont
= customizedFont(styleOption().font
);
916 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
918 updateExpansionArea();
922 m_dirtyLayout
= false;
923 m_dirtyContent
= false;
924 m_dirtyContentRoles
.clear();
927 void KStandardItemListWidget::updateExpansionArea()
929 if (m_supportsItemExpanding
) {
930 const QHash
<QByteArray
, QVariant
> values
= data();
931 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
932 if (expandedParentsCount
>= 0) {
933 const KItemListStyleOption
& option
= styleOption();
934 const qreal widgetHeight
= size().height();
935 const qreal inc
= (widgetHeight
- option
.iconSize
) / 2;
936 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
938 m_expansionArea
= QRectF(x
, y
, option
.iconSize
, option
.iconSize
);
943 m_expansionArea
= QRectF();
946 void KStandardItemListWidget::updatePixmapCache()
948 // Precondition: Requires already updated m_textPos values to calculate
949 // the remaining height when the alignment is vertical.
951 const QSizeF widgetSize
= size();
952 const bool iconOnTop
= (m_layout
== IconsLayout
);
953 const KItemListStyleOption
& option
= styleOption();
954 const qreal padding
= option
.padding
;
956 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
957 const int maxIconHeight
= option
.iconSize
;
959 const QHash
<QByteArray
, QVariant
> values
= data();
961 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
962 if (!updatePixmap
&& m_dirtyContent
) {
963 updatePixmap
= m_dirtyContentRoles
.isEmpty()
964 || m_dirtyContentRoles
.contains("iconPixmap")
965 || m_dirtyContentRoles
.contains("iconName")
966 || m_dirtyContentRoles
.contains("iconOverlays");
970 m_pixmap
= QPixmap();
972 int sequenceIndex
= hoverSequenceIndex();
974 if (values
.contains("hoverSequencePixmaps")) {
975 // Use one of the hover sequence pixmaps instead of the default
978 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
980 if (values
.contains("hoverSequenceWraparoundPoint")) {
981 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
983 sequenceIndex
%= static_cast<int>(wap
);
987 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
989 if (loadedIndex
!= 0) {
990 m_pixmap
= pixmaps
[loadedIndex
];
994 if (m_pixmap
.isNull()) {
995 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
998 if (m_pixmap
.isNull()) {
999 // Use the icon that fits to the MIME-type
1000 QString iconName
= values
["iconName"].toString();
1001 if (iconName
.isEmpty()) {
1002 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1003 // use a generic icon as fallback
1004 iconName
= QStringLiteral("unknown");
1006 const QStringList overlays
= values
["iconOverlays"].toStringList();
1007 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1009 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1010 // A custom pixmap has been applied. Assure that the pixmap
1011 // is scaled to the maximum available size.
1012 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1015 if (m_pixmap
.isNull()) {
1016 m_hoverPixmap
= QPixmap();
1021 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1022 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1026 KIconEffect::semiTransparent(m_pixmap
);
1029 if (m_layout
== IconsLayout
&& isSelected()) {
1030 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1031 QImage image
= m_pixmap
.toImage();
1032 if (image
.isNull()) {
1033 m_hoverPixmap
= QPixmap();
1036 KIconEffect::colorize(image
, color
, 0.8f
);
1037 m_pixmap
= QPixmap::fromImage(image
);
1041 if (!m_overlay
.isNull()) {
1042 QPainter
painter(&m_pixmap
);
1043 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1046 int scaledIconSize
= 0;
1048 const TextInfo
* textInfo
= m_textInfo
.value("text");
1049 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1051 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1052 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1053 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1054 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1057 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1058 const int maxScaledIconHeight
= scaledIconSize
;
1060 m_scaledPixmapSize
= m_pixmap
.size();
1061 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1062 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1065 // Center horizontally and align on bottom within the icon-area
1066 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1067 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1069 // Center horizontally and vertically within the icon-area
1070 const TextInfo
* textInfo
= m_textInfo
.value("text");
1071 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1072 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1074 // Derive icon's vertical center from the center of the text frame, including
1075 // any necessary adjustment if the font's midline is offset from the frame center
1076 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1077 - m_customizedFontMetrics
.descent()
1078 - m_customizedFontMetrics
.capHeight() / 2.0;
1079 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1083 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1085 // Prepare the pixmap that is used when the item gets hovered
1087 m_hoverPixmap
= m_pixmap
;
1088 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1089 // In the KIconLoader terminology, active = hover.
1090 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1091 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1093 m_hoverPixmap
= m_pixmap
;
1095 } else if (hoverOpacity() <= 0.0) {
1096 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1097 m_hoverPixmap
= QPixmap();
1101 void KStandardItemListWidget::updateTextsCache()
1103 QTextOption textOption
;
1106 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1107 textOption
.setAlignment(Qt::AlignHCenter
);
1111 textOption
.setAlignment(Qt::AlignLeft
);
1112 textOption
.setWrapMode(QTextOption::NoWrap
);
1119 qDeleteAll(m_textInfo
);
1121 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1122 TextInfo
* textInfo
= new TextInfo();
1123 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1124 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1125 textInfo
->staticText
.setTextOption(textOption
);
1126 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1130 case IconsLayout
: updateIconsLayoutTextCache(); break;
1131 case CompactLayout
: updateCompactLayoutTextCache(); break;
1132 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1133 default: Q_ASSERT(false); break;
1136 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1137 if (ratingTextInfo
) {
1138 // The text of the rating-role has been set to empty to get
1139 // replaced by a rating-image showing the rating as stars.
1140 const KItemListStyleOption
& option
= styleOption();
1141 QSizeF ratingSize
= preferredRatingSize(option
);
1143 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1144 ? columnWidth("rating") - columnPadding(option
)
1146 if (ratingSize
.width() > availableWidth
) {
1147 ratingSize
.rwidth() = availableWidth
;
1149 const qreal dpr
= qApp
->devicePixelRatio();
1150 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1151 m_rating
.setDevicePixelRatio(dpr
);
1152 m_rating
.fill(Qt::transparent
);
1154 QPainter
painter(&m_rating
);
1155 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1156 const int rating
= data().value("rating").toInt();
1157 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1158 } else if (!m_rating
.isNull()) {
1159 m_rating
= QPixmap();
1163 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1165 const auto extensionIndex
= text
.lastIndexOf('.');
1166 if (extensionIndex
!= -1) {
1167 // has file extension
1168 const auto extensionLength
= text
.length() - extensionIndex
;
1169 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1170 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1171 // if we have room to display the file extension and the extension is not too long
1172 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1174 elidingWidth
- extensionWidth
);
1175 ret
.append(text
.rightRef(extensionLength
));
1179 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1183 void KStandardItemListWidget::updateIconsLayoutTextCache()
1190 // might get wrapped above
1192 // Additional role 1
1193 // Additional role 2
1195 const QHash
<QByteArray
, QVariant
> values
= data();
1197 const KItemListStyleOption
& option
= styleOption();
1198 const qreal padding
= option
.padding
;
1199 const qreal maxWidth
= size().width() - 2 * padding
;
1200 const qreal widgetHeight
= size().height();
1201 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1203 // Initialize properties for the "text" role. It will be used as anchor
1204 // for initializing the position of the other roles.
1205 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1206 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1207 nameTextInfo
->staticText
.setText(nameText
);
1209 // Calculate the number of lines required for the name and the required width
1210 qreal nameWidth
= 0;
1211 qreal nameHeight
= 0;
1214 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1215 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1216 layout
.beginLayout();
1217 int nameLineIndex
= 0;
1218 while ((line
= layout
.createLine()).isValid()) {
1219 line
.setLineWidth(maxWidth
);
1220 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1221 nameHeight
+= line
.height();
1224 if (nameLineIndex
== option
.maxTextLines
) {
1225 // The maximum number of textlines has been reached. If this is
1226 // the case provide an elided text if necessary.
1227 const int textLength
= line
.textStart() + line
.textLength();
1228 if (textLength
< nameText
.length()) {
1229 // Elide the last line of the text
1230 qreal elidingWidth
= maxWidth
;
1231 qreal lastLineWidth
;
1233 QString lastTextLine
= nameText
.mid(line
.textStart());
1234 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1235 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1236 nameTextInfo
->staticText
.setText(elidedText
);
1238 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1240 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1241 // to avoid problems related to different width calculation code paths
1242 // within Qt. (see bug 337104)
1243 elidingWidth
-= 1.0;
1244 } while (lastLineWidth
> maxWidth
);
1246 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1253 // Use one line for each additional information
1254 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1255 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1256 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1258 additionalRolesCount
* lineSpacing
-
1260 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1261 nameTextInfo
->pos
.y(),
1265 // Calculate the position for each additional information
1266 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1267 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1268 if (role
== "text") {
1272 const QString text
= roleText(role
, values
);
1273 TextInfo
* textInfo
= m_textInfo
.value(role
);
1274 textInfo
->staticText
.setText(text
);
1276 qreal requiredWidth
= 0;
1278 QTextLayout
layout(text
, m_customizedFont
);
1279 QTextOption textOption
;
1280 textOption
.setWrapMode(QTextOption::NoWrap
);
1281 layout
.setTextOption(textOption
);
1283 layout
.beginLayout();
1284 QTextLine textLine
= layout
.createLine();
1285 if (textLine
.isValid()) {
1286 textLine
.setLineWidth(maxWidth
);
1287 requiredWidth
= textLine
.naturalTextWidth();
1288 if (requiredWidth
> maxWidth
) {
1289 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1290 textInfo
->staticText
.setText(elidedText
);
1291 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1292 } else if (role
== "rating") {
1293 // Use the width of the rating pixmap, because the rating text is empty.
1294 requiredWidth
= m_rating
.width();
1299 textInfo
->pos
= QPointF(padding
, y
);
1300 textInfo
->staticText
.setTextWidth(maxWidth
);
1302 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1303 m_textRect
|= textRect
;
1308 // Add a padding to the text rectangle
1309 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1312 void KStandardItemListWidget::updateCompactLayoutTextCache()
1314 // +------+ Name role
1315 // | Icon | Additional role 1
1316 // +------+ Additional role 2
1318 const QHash
<QByteArray
, QVariant
> values
= data();
1320 const KItemListStyleOption
& option
= styleOption();
1321 const qreal widgetHeight
= size().height();
1322 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1323 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1324 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1326 qreal maximumRequiredTextWidth
= 0;
1327 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1328 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1329 const qreal maxWidth
= size().width() - x
- option
.padding
;
1330 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1331 const QString text
= roleText(role
, values
);
1332 TextInfo
* textInfo
= m_textInfo
.value(role
);
1333 textInfo
->staticText
.setText(text
);
1335 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1336 if (requiredWidth
> maxWidth
) {
1337 requiredWidth
= maxWidth
;
1338 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1339 textInfo
->staticText
.setText(elidedText
);
1342 textInfo
->pos
= QPointF(x
, y
);
1343 textInfo
->staticText
.setTextWidth(maxWidth
);
1345 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1350 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1353 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1355 // Precondition: Requires already updated m_expansionArea
1356 // to determine the left position.
1359 // | Icon | Name role Additional role 1 Additional role 2
1361 m_textRect
= QRectF();
1363 const KItemListStyleOption
& option
= styleOption();
1364 const QHash
<QByteArray
, QVariant
> values
= data();
1366 const qreal widgetHeight
= size().height();
1367 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1368 const int fontHeight
= m_customizedFontMetrics
.height();
1370 const qreal columnWidthInc
= columnPadding(option
);
1371 qreal firstColumnInc
= scaledIconSize
;
1372 if (m_supportsItemExpanding
) {
1373 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1375 firstColumnInc
+= option
.padding
;
1378 qreal x
= firstColumnInc
;
1379 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1381 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1382 QString text
= roleText(role
, values
);
1384 // Elide the text in case it does not fit into the available column-width
1385 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1386 const qreal roleWidth
= columnWidth(role
);
1387 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1389 const bool isTextRole
= (role
== "text");
1391 availableTextWidth
-= firstColumnInc
;
1394 if (requiredWidth
> availableTextWidth
) {
1395 text
= elideRightKeepExtension(text
, availableTextWidth
);
1396 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1399 TextInfo
* textInfo
= m_textInfo
.value(role
);
1400 textInfo
->staticText
.setText(text
);
1401 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1405 const qreal textWidth
= option
.extendedSelectionRegion
1406 ? size().width() - textInfo
->pos
.x()
1407 : requiredWidth
+ 2 * option
.padding
;
1408 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1409 textWidth
, size().height());
1411 // The column after the name should always be aligned on the same x-position independent
1412 // from the expansion-level shown in the name column
1413 x
-= firstColumnInc
;
1414 } else if (isRoleRightAligned(role
)) {
1415 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1420 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1423 if (m_customTextColor
.isValid()) {
1424 c1
= m_customTextColor
;
1425 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1426 c1
= styleOption().palette
.highlightedText().color();
1428 c1
= styleOption().palette
.text().color();
1431 // For the color of the additional info the inactive text color
1432 // is not used as this might lead to unreadable text for some color schemes. Instead
1433 // the text color c1 is slightly mixed with the background color.
1434 const QColor c2
= styleOption().palette
.base().color();
1436 const int p2
= 100 - p1
;
1437 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1438 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1439 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1442 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1444 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1445 QPixmap scaledPixmap
= pixmap
;
1446 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1447 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1448 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1450 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1451 painter
->setPen(Qt::blue
);
1452 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1455 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1459 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1461 const int siblingSize
= size().height();
1462 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1463 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1465 QStyleOption option
;
1466 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1467 bool isItemSibling
= true;
1469 const QBitArray siblings
= siblingsInformation();
1470 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1471 option
.rect
= siblingRect
;
1472 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1474 if (isItemSibling
) {
1475 option
.state
|= QStyle::State_Item
;
1476 if (m_isExpandable
) {
1477 option
.state
|= QStyle::State_Children
;
1479 if (data().value("isExpanded").toBool()) {
1480 option
.state
|= QStyle::State_Open
;
1482 isItemSibling
= false;
1485 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1487 siblingRect
.translate(-siblingRect
.width(), 0);
1491 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1493 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1498 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1499 if (m_layout
== DetailsLayout
) {
1500 rect
.setWidth(columnWidth(role
) - rect
.x());
1506 void KStandardItemListWidget::closeRoleEditor()
1508 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1509 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1510 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1511 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1513 if (m_roleEditor
->hasFocus()) {
1514 // If the editing was not ended by a FocusOut event, we have
1515 // to transfer the keyboard focus back to the KItemListContainer.
1516 scene()->views()[0]->parentWidget()->setFocus();
1519 if (m_oldRoleEditor
) {
1520 m_oldRoleEditor
->deleteLater();
1522 m_oldRoleEditor
= m_roleEditor
;
1523 m_roleEditor
->hide();
1524 m_roleEditor
= nullptr;
1527 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1529 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1531 size
*= qApp
->devicePixelRatio();
1533 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1536 if (!QPixmapCache::find(key
, &pixmap
)) {
1537 QIcon icon
= QIcon::fromTheme(name
);
1538 if (icon
.isNull()) {
1542 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1543 icon
= fallbackIcon
;
1546 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1547 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1548 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1551 // Strangely KFileItem::overlays() returns empty string-values, so
1552 // we need to check first whether an overlay must be drawn at all.
1553 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1554 // assumes that an overlay will be drawn and has some additional
1556 for (const QString
& overlay
: overlays
) {
1557 if (!overlay
.isEmpty()) {
1558 int state
= KIconLoader::DefaultState
;
1564 state
= KIconLoader::ActiveState
;
1566 case QIcon::Disabled
:
1567 state
= KIconLoader::DisabledState
;
1569 case QIcon::Selected
:
1570 state
= KIconLoader::SelectedState
;
1574 // There is at least one overlay, draw all overlays above m_pixmap
1575 // and cancel the check
1576 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1581 QPixmapCache::insert(key
, pixmap
);
1583 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1588 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1590 const qreal height
= option
.fontMetrics
.ascent();
1591 return QSizeF(height
* 5, height
);
1594 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1596 return option
.padding
* 6;