2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QPixmapCache>
25 #include <QStyleOption>
27 // #define KSTANDARDITEMLISTWIDGET_DEBUG
29 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
30 : KItemListWidgetInformant()
34 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
38 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
39 qreal
&logicalWidthHint
,
40 const KItemListView
*view
) const
42 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
43 case KStandardItemListView::IconsLayout
:
44 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
47 case KStandardItemListView::CompactLayout
:
48 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
51 case KStandardItemListView::DetailsLayout
:
52 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
61 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
63 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
64 const KItemListStyleOption
&option
= view
->styleOption();
66 const QString text
= roleText(role
, values
);
67 qreal width
= KStandardItemListWidget::columnPadding(option
);
69 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
70 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
72 if (role
== "rating") {
73 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
75 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
76 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
78 width
+= fontMetrics
.horizontalAdvance(text
);
81 if (view
->supportsItemExpanding()) {
82 // Increase the width by the expansion-toggle and the current expansion level
83 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
84 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
85 width
+= (expandedParentsCount
+ 1) * height
;
88 // Increase the width by the required space for the icon
89 width
+= option
.padding
* 2 + option
.iconSize
;
96 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
98 return view
->model()->data(index
).value("text").toString();
101 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
108 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
110 if (role
== "rating") {
111 // Always use an empty text, as the rating is shown by the image m_rating.
114 return values
.value(role
).toString();
117 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
122 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
123 qreal
&logicalWidthHint
,
124 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
,
182 qreal
&logicalWidthHint
,
183 const KItemListView
*view
) const
185 const KItemListStyleOption
&option
= view
->styleOption();
186 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
187 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
189 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
190 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
191 const qreal maxWidth
= option
.maxTextWidth
;
192 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
193 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
195 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
197 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
198 if (logicalHeightHints
.at(index
).first
> 0.0) {
202 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
203 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
205 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
206 // to show all roles without horizontal clipping.
207 qreal maximumRequiredWidth
= 0.0;
209 if (showOnlyTextRole
) {
210 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
212 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
213 for (const QByteArray
&role
: visibleRoles
) {
214 const QString
&text
= roleText(role
, values
);
215 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
216 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
220 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
221 if (maxWidth
> 0 && width
> maxWidth
) {
225 logicalHeightHints
[index
].first
= width
;
228 logicalWidthHint
= height
;
231 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
232 qreal
&logicalWidthHint
,
233 const KItemListView
*view
) const
235 const KItemListStyleOption
&option
= view
->styleOption();
236 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
237 logicalHeightHints
.fill(std::make_pair(height
, false));
238 logicalWidthHint
= -1.0;
241 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
242 : KItemListWidget(informant
, parent
)
247 , m_customizedFontMetrics(m_customizedFont
)
248 , m_isExpandable(false)
249 , m_highlightEntireRow(false)
250 , m_supportsItemExpanding(false)
251 , m_dirtyLayout(true)
252 , m_dirtyContent(true)
253 , m_dirtyContentRoles()
254 , m_layout(IconsLayout
)
257 , m_scaledPixmapSize()
262 , m_sortedVisibleRoles()
264 , m_customTextColor()
265 , m_additionalInfoTextColor()
268 , m_roleEditor(nullptr)
269 , m_oldRoleEditor(nullptr)
273 KStandardItemListWidget::~KStandardItemListWidget()
275 qDeleteAll(m_textInfo
);
279 m_roleEditor
->deleteLater();
282 if (m_oldRoleEditor
) {
283 m_oldRoleEditor
->deleteLater();
287 void KStandardItemListWidget::setLayout(Layout layout
)
289 if (m_layout
!= layout
) {
291 m_dirtyLayout
= true;
292 updateAdditionalInfoTextColor();
297 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
302 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
304 if (m_highlightEntireRow
!= highlightEntireRow
) {
305 m_highlightEntireRow
= highlightEntireRow
;
306 m_dirtyLayout
= true;
311 bool KStandardItemListWidget::highlightEntireRow() const
313 return m_highlightEntireRow
;
316 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
318 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
319 m_supportsItemExpanding
= supportsItemExpanding
;
320 m_dirtyLayout
= true;
325 bool KStandardItemListWidget::supportsItemExpanding() const
327 return m_supportsItemExpanding
;
330 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
332 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
334 KItemListWidget::paint(painter
, option
, widget
);
336 if (!m_expansionArea
.isEmpty()) {
337 drawSiblingsInformation(painter
);
340 const KItemListStyleOption
&itemListStyleOption
= styleOption();
341 if (isHovered() && !m_pixmap
.isNull()) {
342 if (hoverOpacity() < 1.0) {
344 * Linear interpolation between m_pixmap and m_hoverPixmap.
346 * Note that this cannot be achieved by painting m_hoverPixmap over
347 * m_pixmap, even if the opacities are adjusted. For details see
348 * https://git.reviewboard.kde.org/r/109614/
350 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
351 QPixmap
pixmap1(m_pixmap
.size());
352 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
353 pixmap1
.fill(Qt::transparent
);
355 QPainter
p(&pixmap1
);
356 p
.setOpacity(1.0 - hoverOpacity());
357 p
.drawPixmap(0, 0, m_pixmap
);
360 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
361 QPixmap
pixmap2(pixmap1
.size());
362 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
363 pixmap2
.fill(Qt::transparent
);
365 QPainter
p(&pixmap2
);
366 p
.setOpacity(hoverOpacity());
367 p
.drawPixmap(0, 0, m_hoverPixmap
);
370 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
371 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
372 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
374 QPainter
p(&pixmap1
);
375 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
376 p
.drawPixmap(0, 0, pixmap2
);
379 // Finally paint pixmap1 on the widget
380 drawPixmap(painter
, pixmap1
);
382 drawPixmap(painter
, m_hoverPixmap
);
384 } else if (!m_pixmap
.isNull()) {
385 drawPixmap(painter
, m_pixmap
);
388 painter
->setFont(m_customizedFont
);
389 painter
->setPen(textColor(*widget
));
390 const TextInfo
*textInfo
= m_textInfo
.value("text");
393 // It seems that we can end up here even if m_textInfo does not contain
394 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
395 // this can only happen if the index is negative. This can happen when
396 // the item is about to be removed, see KItemListView::slotItemsRemoved().
397 // TODO: try to reproduce the crash and find a better fix.
401 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
403 bool clipAdditionalInfoBounds
= false;
404 if (m_supportsItemExpanding
) {
405 // Prevent a possible overlapping of the additional-information texts
406 // with the icon. This can happen if the user has minimized the width
407 // of the name-column to a very small value.
408 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
409 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
410 clipAdditionalInfoBounds
= true;
412 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
416 painter
->setPen(m_additionalInfoTextColor
);
417 painter
->setFont(m_customizedFont
);
419 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
420 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
421 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
424 if (!m_rating
.isNull()) {
425 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
426 QPointF pos
= ratingTextInfo
->pos
;
427 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
428 if (align
& Qt::AlignHCenter
) {
429 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
431 painter
->drawPixmap(pos
, m_rating
);
434 if (clipAdditionalInfoBounds
) {
438 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
439 painter
->setBrush(Qt::NoBrush
);
440 painter
->setPen(Qt::green
);
441 painter
->drawRect(m_iconRect
);
443 painter
->setPen(Qt::blue
);
444 painter
->drawRect(m_textRect
);
446 painter
->setPen(Qt::red
);
447 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
448 painter
->drawRect(rect());
452 QRectF
KStandardItemListWidget::iconRect() const
454 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
458 QRectF
KStandardItemListWidget::textRect() const
460 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
464 QRectF
KStandardItemListWidget::textFocusRect() const
466 // In the compact- and details-layout a larger textRect() is returned to be aligned
467 // with the iconRect(). This is useful to have a larger selection/hover-area
468 // when having a quite large icon size but only one line of text. Still the
469 // focus rectangle should be shown as narrow as possible around the text.
471 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
474 case CompactLayout
: {
475 QRectF rect
= m_textRect
;
476 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
477 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
478 rect
.setTop(topText
->pos
.y());
479 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
483 case DetailsLayout
: {
484 QRectF rect
= m_textRect
;
485 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
486 rect
.setTop(textInfo
->pos
.y());
487 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
489 const KItemListStyleOption
&option
= styleOption();
490 if (option
.extendedSelectionRegion
) {
491 const QString text
= textInfo
->staticText
.text();
492 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
505 QRectF
KStandardItemListWidget::selectionRect() const
507 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
514 case DetailsLayout
: {
515 const int padding
= styleOption().padding
;
516 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
517 QRectF result
= adjustedIconRect
| m_textRect
;
518 if (m_highlightEntireRow
) {
519 result
.setRight(m_columnWidthSum
+ sidePadding());
532 QRectF
KStandardItemListWidget::expansionToggleRect() const
534 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
535 return m_isExpandable
? m_expansionArea
: QRectF();
538 QRectF
KStandardItemListWidget::selectionToggleRect() const
540 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
542 const int widgetIconSize
= iconSize();
543 int toggleSize
= KIconLoader::SizeSmall
;
544 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
545 toggleSize
= KIconLoader::SizeMedium
;
546 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
547 toggleSize
= KIconLoader::SizeSmallMedium
;
550 QPointF pos
= iconRect().topLeft();
552 // If the selection toggle has a very small distance to the
553 // widget borders, the size of the selection toggle will get
554 // increased to prevent an accidental clicking of the item
555 // when trying to hit the toggle.
556 const int widgetHeight
= size().height();
557 const int widgetWidth
= size().width();
558 const int minMargin
= 2;
560 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
561 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
562 toggleSize
= widgetHeight
;
565 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
566 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
567 toggleSize
= widgetWidth
;
571 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
574 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
576 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
577 if (m_layout
!= DetailsLayout
) {
581 // Only return the content of the text-column as pixmap
582 const int leftClip
= m_pixmapPos
.x();
584 const TextInfo
*textInfo
= m_textInfo
.value("text");
585 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
587 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
588 clippedPixmap
.fill(Qt::transparent
);
590 QPainter
painter(&clippedPixmap
);
591 painter
.drawPixmap(-leftClip
, 0, pixmap
);
593 return clippedPixmap
;
596 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
598 return new KStandardItemListWidgetInformant();
601 void KStandardItemListWidget::invalidateCache()
603 m_dirtyLayout
= true;
604 m_dirtyContent
= true;
607 void KStandardItemListWidget::invalidateIconCache()
609 m_dirtyContent
= true;
610 m_dirtyContentRoles
.insert("iconPixmap");
611 m_dirtyContentRoles
.insert("iconOverlays");
614 void KStandardItemListWidget::refreshCache()
618 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
624 bool KStandardItemListWidget::isHidden() const
629 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
634 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
636 return QPalette::Text
;
639 void KStandardItemListWidget::setTextColor(const QColor
&color
)
641 if (color
!= m_customTextColor
) {
642 m_customTextColor
= color
;
643 updateAdditionalInfoTextColor();
648 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
652 return m_additionalInfoTextColor
;
653 } else if (m_customTextColor
.isValid()) {
654 return m_customTextColor
;
658 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
659 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
660 return styleOption().palette
.color(group
, role
);
663 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
666 m_dirtyContent
= true;
670 QPixmap
KStandardItemListWidget::overlay() const
675 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
677 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
680 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
684 m_dirtyContent
= true;
686 QSet
<QByteArray
> dirtyRoles
;
687 if (roles
.isEmpty()) {
688 const auto visibleRoles
= this->visibleRoles();
689 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
694 // The URL might have changed (i.e., if the sort order of the items has
695 // been changed). Therefore, the "is cut" state must be updated.
696 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
697 const QUrl itemUrl
= data().value("url").toUrl();
698 m_isCut
= clipboard
->isCut(itemUrl
);
700 // The icon-state might depend from other roles and hence is
701 // marked as dirty whenever a role has been changed
702 dirtyRoles
.insert("iconPixmap");
703 dirtyRoles
.insert("iconName");
705 QSetIterator
<QByteArray
> it(dirtyRoles
);
706 while (it
.hasNext()) {
707 const QByteArray
&role
= it
.next();
708 m_dirtyContentRoles
.insert(role
);
712 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
715 m_sortedVisibleRoles
= current
;
716 m_dirtyLayout
= true;
719 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
724 m_dirtyLayout
= true;
727 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
730 m_dirtyLayout
= true;
733 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
735 KItemListWidget::styleOptionChanged(current
, previous
);
737 updateAdditionalInfoTextColor();
738 m_dirtyLayout
= true;
741 void KStandardItemListWidget::hoveredChanged(bool hovered
)
744 m_dirtyLayout
= true;
747 void KStandardItemListWidget::selectedChanged(bool selected
)
750 updateAdditionalInfoTextColor();
751 m_dirtyContent
= true;
754 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
758 m_dirtyLayout
= true;
761 int KStandardItemListWidget::selectionLength(const QString
&text
) const
763 return text
.length();
766 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
770 QGraphicsView
*parent
= scene()->views()[0];
771 if (current
.isEmpty() || !parent
|| current
!= "text") {
773 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
775 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
776 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
778 if (m_oldRoleEditor
) {
779 m_oldRoleEditor
->deleteLater();
781 m_oldRoleEditor
= m_roleEditor
;
782 m_roleEditor
->hide();
783 m_roleEditor
= nullptr;
788 Q_ASSERT(!m_roleEditor
);
790 const TextInfo
*textInfo
= m_textInfo
.value("text");
792 m_roleEditor
= new KItemListRoleEditor(parent
);
793 m_roleEditor
->setRole(current
);
794 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
795 m_roleEditor
->setFont(styleOption().font
);
797 const QString text
= data().value(current
).toString();
798 m_roleEditor
->setPlainText(text
);
800 QTextOption textOption
= textInfo
->staticText
.textOption();
801 m_roleEditor
->document()->setDefaultTextOption(textOption
);
803 const int textSelectionLength
= selectionLength(text
);
805 if (textSelectionLength
> 0) {
806 QTextCursor cursor
= m_roleEditor
->textCursor();
807 cursor
.movePosition(QTextCursor::StartOfBlock
);
808 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
809 m_roleEditor
->setTextCursor(cursor
);
812 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
813 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
815 // Adjust the geometry of the editor
816 QRectF rect
= roleEditingRect(current
);
817 const int frameWidth
= m_roleEditor
->frameWidth();
818 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
819 rect
.translate(pos());
820 if (rect
.right() > parent
->width()) {
821 rect
.setWidth(parent
->width() - rect
.left());
823 m_roleEditor
->setGeometry(rect
.toRect());
824 m_roleEditor
->autoAdjustSize();
825 m_roleEditor
->show();
826 m_roleEditor
->setFocus();
829 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
831 KItemListWidget::iconSizeChanged(current
, previous
);
833 invalidateIconCache();
834 triggerCacheRefreshing();
838 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
841 setEditedRole(QByteArray());
842 Q_ASSERT(!m_roleEditor
);
845 KItemListWidget::resizeEvent(event
);
847 m_dirtyLayout
= true;
850 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
852 KItemListWidget::showEvent(event
);
854 // Listen to changes of the clipboard to mark the item as cut/uncut
855 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
857 const QUrl itemUrl
= data().value("url").toUrl();
858 m_isCut
= clipboard
->isCut(itemUrl
);
860 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
863 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
865 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
867 KItemListWidget::hideEvent(event
);
870 bool KStandardItemListWidget::event(QEvent
*event
)
872 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
873 m_dirtyContent
= true;
876 return KItemListWidget::event(event
);
879 void KStandardItemListWidget::finishRoleEditing()
881 if (!editedRole().isEmpty() && m_roleEditor
) {
882 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
886 void KStandardItemListWidget::slotCutItemsChanged()
888 const QUrl itemUrl
= data().value("url").toUrl();
889 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
890 if (m_isCut
!= isCut
) {
892 m_pixmap
= QPixmap();
893 m_dirtyContent
= true;
898 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
901 Q_EMIT
roleEditingCanceled(index(), role
, value
);
902 setEditedRole(QByteArray());
905 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
908 Q_EMIT
roleEditingFinished(index(), role
, value
);
909 setEditedRole(QByteArray());
912 void KStandardItemListWidget::triggerCacheRefreshing()
914 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
920 const QHash
<QByteArray
, QVariant
> values
= data();
921 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
922 m_isHidden
= isHidden();
923 m_customizedFont
= customizedFont(styleOption().font
);
924 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
925 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
926 return sum
+ columnWidth(role
);
929 updateExpansionArea();
934 m_dirtyLayout
= false;
935 m_dirtyContent
= false;
936 m_dirtyContentRoles
.clear();
939 void KStandardItemListWidget::updateExpansionArea()
941 if (m_supportsItemExpanding
) {
942 const QHash
<QByteArray
, QVariant
> values
= data();
943 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
944 if (expandedParentsCount
>= 0) {
945 const int widgetIconSize
= iconSize();
946 const qreal widgetHeight
= size().height();
947 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
948 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
950 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
951 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
956 m_expansionArea
= QRectF();
959 void KStandardItemListWidget::updatePixmapCache()
961 // Precondition: Requires already updated m_textPos values to calculate
962 // the remaining height when the alignment is vertical.
964 const QSizeF widgetSize
= size();
965 const bool iconOnTop
= (m_layout
== IconsLayout
);
966 const KItemListStyleOption
&option
= styleOption();
967 const qreal padding
= option
.padding
;
969 const int widgetIconSize
= iconSize();
970 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
971 const int maxIconHeight
= widgetIconSize
;
973 const QHash
<QByteArray
, QVariant
> values
= data();
975 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
976 if (!updatePixmap
&& m_dirtyContent
) {
977 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
978 || m_dirtyContentRoles
.contains("iconOverlays");
982 m_pixmap
= QPixmap();
984 int sequenceIndex
= hoverSequenceIndex();
986 if (values
.contains("hoverSequencePixmaps")) {
987 // Use one of the hover sequence pixmaps instead of the default
990 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
992 if (values
.contains("hoverSequenceWraparoundPoint")) {
993 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
995 sequenceIndex
%= static_cast<int>(wap
);
999 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1001 if (loadedIndex
!= 0) {
1002 m_pixmap
= pixmaps
[loadedIndex
];
1006 if (m_pixmap
.isNull()) {
1007 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1010 if (m_pixmap
.isNull()) {
1011 // Use the icon that fits to the MIME-type
1012 QString iconName
= values
["iconName"].toString();
1013 if (iconName
.isEmpty()) {
1014 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1015 // use a generic icon as fallback
1016 iconName
= QStringLiteral("unknown");
1018 const QStringList overlays
= values
["iconOverlays"].toStringList();
1019 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1020 m_pixmap
= pixmapForIcon(iconName
,
1023 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1025 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1026 // A custom pixmap has been applied. Assure that the pixmap
1027 // is scaled to the maximum available size.
1028 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1031 if (m_pixmap
.isNull()) {
1032 m_hoverPixmap
= QPixmap();
1037 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1038 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1042 KIconEffect::semiTransparent(m_pixmap
);
1045 if (m_layout
== IconsLayout
&& isSelected()) {
1046 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1047 QImage image
= m_pixmap
.toImage();
1048 if (image
.isNull()) {
1049 m_hoverPixmap
= QPixmap();
1052 KIconEffect::colorize(image
, color
, 0.8f
);
1053 m_pixmap
= QPixmap::fromImage(image
);
1057 if (!m_overlay
.isNull()) {
1058 QPainter
painter(&m_pixmap
);
1059 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1062 int scaledIconSize
= 0;
1064 const TextInfo
*textInfo
= m_textInfo
.value("text");
1065 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1067 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1068 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1069 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? 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
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1088 // Derive icon's vertical center from the center of the text frame, including
1089 // any necessary adjustment if the font's midline is offset from the frame center
1090 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1091 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1094 if (m_layout
== IconsLayout
) {
1095 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1097 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1098 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1099 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1100 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1101 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1104 // Prepare the pixmap that is used when the item gets hovered
1106 m_hoverPixmap
= m_pixmap
;
1107 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1108 // In the KIconLoader terminology, active = hover.
1109 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1110 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1112 m_hoverPixmap
= m_pixmap
;
1114 } else if (hoverOpacity() <= 0.0) {
1115 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1116 m_hoverPixmap
= QPixmap();
1120 void KStandardItemListWidget::updateTextsCache()
1122 QTextOption textOption
;
1125 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1126 textOption
.setAlignment(Qt::AlignHCenter
);
1130 textOption
.setAlignment(Qt::AlignLeft
);
1131 textOption
.setWrapMode(QTextOption::NoWrap
);
1138 qDeleteAll(m_textInfo
);
1140 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1141 TextInfo
*textInfo
= new TextInfo();
1142 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1143 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1144 textInfo
->staticText
.setTextOption(textOption
);
1145 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1150 updateIconsLayoutTextCache();
1153 updateCompactLayoutTextCache();
1156 updateDetailsLayoutTextCache();
1163 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1164 if (ratingTextInfo
) {
1165 // The text of the rating-role has been set to empty to get
1166 // replaced by a rating-image showing the rating as stars.
1167 const KItemListStyleOption
&option
= styleOption();
1168 QSizeF ratingSize
= preferredRatingSize(option
);
1170 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1171 if (ratingSize
.width() > availableWidth
) {
1172 ratingSize
.rwidth() = availableWidth
;
1174 const qreal dpr
= qApp
->devicePixelRatio();
1175 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1176 m_rating
.setDevicePixelRatio(dpr
);
1177 m_rating
.fill(Qt::transparent
);
1179 QPainter
painter(&m_rating
);
1180 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1181 const int rating
= data().value("rating").toInt();
1182 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1183 } else if (!m_rating
.isNull()) {
1184 m_rating
= QPixmap();
1188 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1190 const auto extensionIndex
= text
.lastIndexOf('.');
1191 if (extensionIndex
!= -1) {
1192 // has file extension
1193 const auto extensionLength
= text
.length() - extensionIndex
;
1194 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1195 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1196 // if we have room to display the file extension and the extension is not too long
1197 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1198 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1199 ret
.append(text
.rightRef(extensionLength
));
1201 ret
.append(QStringView(text
).right(extensionLength
));
1206 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1209 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1211 QString
escaped(text
);
1213 const QChar
returnSymbol(0x21b5);
1214 escaped
.replace('\n', returnSymbol
);
1219 void KStandardItemListWidget::updateIconsLayoutTextCache()
1226 // might get wrapped above
1228 // Additional role 1
1229 // Additional role 2
1231 const QHash
<QByteArray
, QVariant
> values
= data();
1233 const KItemListStyleOption
&option
= styleOption();
1234 const qreal padding
= option
.padding
;
1235 const qreal maxWidth
= size().width() - 2 * padding
;
1236 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1238 // Initialize properties for the "text" role. It will be used as anchor
1239 // for initializing the position of the other roles.
1240 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1241 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1242 nameTextInfo
->staticText
.setText(nameText
);
1244 // Calculate the number of lines required for the name and the required width
1245 qreal nameWidth
= 0;
1246 qreal nameHeight
= 0;
1249 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1250 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1251 layout
.beginLayout();
1252 int nameLineIndex
= 0;
1253 while ((line
= layout
.createLine()).isValid()) {
1254 line
.setLineWidth(maxWidth
);
1255 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1256 nameHeight
+= line
.height();
1259 if (nameLineIndex
== option
.maxTextLines
) {
1260 // The maximum number of textlines has been reached. If this is
1261 // the case provide an elided text if necessary.
1262 const int textLength
= line
.textStart() + line
.textLength();
1263 if (textLength
< nameText
.length()) {
1264 // Elide the last line of the text
1265 qreal elidingWidth
= maxWidth
;
1266 qreal lastLineWidth
;
1268 QString lastTextLine
= nameText
.mid(line
.textStart());
1269 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1270 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1271 nameTextInfo
->staticText
.setText(elidedText
);
1273 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1275 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1276 // to avoid problems related to different width calculation code paths
1277 // within Qt. (see bug 337104)
1278 elidingWidth
-= 1.0;
1279 } while (lastLineWidth
> maxWidth
);
1281 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1288 // Use one line for each additional information
1289 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1290 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1291 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1293 // Calculate the position for each additional information
1294 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1295 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1296 if (role
== "text") {
1300 const QString text
= roleText(role
, values
);
1301 TextInfo
*textInfo
= m_textInfo
.value(role
);
1302 textInfo
->staticText
.setText(text
);
1304 qreal requiredWidth
= 0;
1306 QTextLayout
layout(text
, m_customizedFont
);
1307 QTextOption textOption
;
1308 textOption
.setWrapMode(QTextOption::NoWrap
);
1309 layout
.setTextOption(textOption
);
1311 layout
.beginLayout();
1312 QTextLine textLine
= layout
.createLine();
1313 if (textLine
.isValid()) {
1314 textLine
.setLineWidth(maxWidth
);
1315 requiredWidth
= textLine
.naturalTextWidth();
1316 if (requiredWidth
> maxWidth
) {
1317 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1318 textInfo
->staticText
.setText(elidedText
);
1319 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1320 } else if (role
== "rating") {
1321 // Use the width of the rating pixmap, because the rating text is empty.
1322 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1327 textInfo
->pos
= QPointF(padding
, y
);
1328 textInfo
->staticText
.setTextWidth(maxWidth
);
1330 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1332 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1333 if (!textRect
.isEmpty()) {
1334 m_textRect
|= textRect
;
1340 // Add a padding to the text rectangle
1341 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1344 void KStandardItemListWidget::updateCompactLayoutTextCache()
1346 // +------+ Name role
1347 // | Icon | Additional role 1
1348 // +------+ Additional role 2
1350 const QHash
<QByteArray
, QVariant
> values
= data();
1352 const KItemListStyleOption
&option
= styleOption();
1353 const qreal widgetHeight
= size().height();
1354 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1355 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1357 qreal maximumRequiredTextWidth
= 0;
1358 const qreal x
= option
.padding
* 3 + iconSize();
1359 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1360 const qreal maxWidth
= size().width() - x
- option
.padding
;
1361 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1362 const QString text
= escapeString(roleText(role
, values
));
1363 TextInfo
*textInfo
= m_textInfo
.value(role
);
1364 textInfo
->staticText
.setText(text
);
1366 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1367 if (requiredWidth
> maxWidth
) {
1368 requiredWidth
= maxWidth
;
1369 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1370 textInfo
->staticText
.setText(elidedText
);
1373 textInfo
->pos
= QPointF(x
, y
);
1374 textInfo
->staticText
.setTextWidth(maxWidth
);
1376 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1381 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1384 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1386 // Precondition: Requires already updated m_expansionArea
1387 // to determine the left position.
1390 // | Icon | Name role Additional role 1 Additional role 2
1392 m_textRect
= QRectF();
1394 const KItemListStyleOption
&option
= styleOption();
1395 const QHash
<QByteArray
, QVariant
> values
= data();
1397 const qreal widgetHeight
= size().height();
1398 const int fontHeight
= m_customizedFontMetrics
.height();
1400 const qreal columnWidthInc
= columnPadding(option
);
1401 qreal firstColumnInc
= iconSize();
1402 if (m_supportsItemExpanding
) {
1403 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1405 firstColumnInc
+= option
.padding
+ sidePadding();
1408 qreal x
= firstColumnInc
;
1409 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1411 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1412 QString text
= roleText(role
, values
);
1414 // Elide the text in case it does not fit into the available column-width
1415 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1416 const qreal roleWidth
= columnWidth(role
);
1417 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1419 const bool isTextRole
= (role
== "text");
1421 text
= escapeString(text
);
1422 availableTextWidth
-= firstColumnInc
- sidePadding();
1425 if (requiredWidth
> availableTextWidth
) {
1426 text
= elideRightKeepExtension(text
, availableTextWidth
);
1427 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1430 TextInfo
*textInfo
= m_textInfo
.value(role
);
1431 textInfo
->staticText
.setText(text
);
1432 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1436 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1437 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1439 // The column after the name should always be aligned on the same x-position independent
1440 // from the expansion-level shown in the name column
1441 x
-= firstColumnInc
- sidePadding();
1442 } else if (isRoleRightAligned(role
)) {
1443 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1448 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1451 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1452 if (m_customTextColor
.isValid()) {
1453 c1
= m_customTextColor
;
1454 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1455 // The detail text colour needs to match the main text (HighlightedText) for the same level
1456 // of readability. We short circuit early here to avoid interpolating with another colour.
1457 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1460 c1
= styleOption().palette
.text().color();
1463 // For the color of the additional info the inactive text color
1464 // is not used as this might lead to unreadable text for some color schemes. Instead
1465 // the text color c1 is slightly mixed with the background color.
1466 const QColor c2
= styleOption().palette
.base().color();
1468 const int p2
= 100 - p1
;
1469 m_additionalInfoTextColor
=
1470 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1473 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1475 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1476 QPixmap scaledPixmap
= pixmap
;
1477 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1478 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1479 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1481 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1482 painter
->setPen(Qt::blue
);
1483 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1486 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1490 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1492 const int siblingSize
= size().height();
1493 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1494 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1496 bool isItemSibling
= true;
1498 const QBitArray siblings
= siblingsInformation();
1499 QStyleOption option
;
1500 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1501 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1502 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1503 option
.rect
= siblingRect
;
1504 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1505 if (isItemSibling
) {
1506 option
.state
|= QStyle::State_Item
;
1507 if (m_isExpandable
) {
1508 option
.state
|= QStyle::State_Children
;
1510 if (data().value("isExpanded").toBool()) {
1511 option
.state
|= QStyle::State_Open
;
1513 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1514 isItemSibling
= false;
1516 option
.palette
.setColor(QPalette::Text
, normalColor
);
1519 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1521 siblingRect
.translate(-siblingRect
.width(), 0);
1525 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1527 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1532 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1533 if (m_layout
== DetailsLayout
) {
1534 rect
.setWidth(columnWidth(role
) - rect
.x());
1540 void KStandardItemListWidget::closeRoleEditor()
1542 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1543 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1545 if (m_roleEditor
->hasFocus()) {
1546 // If the editing was not ended by a FocusOut event, we have
1547 // to transfer the keyboard focus back to the KItemListContainer.
1548 scene()->views()[0]->parentWidget()->setFocus();
1551 if (m_oldRoleEditor
) {
1552 m_oldRoleEditor
->deleteLater();
1554 m_oldRoleEditor
= m_roleEditor
;
1555 m_roleEditor
->hide();
1556 m_roleEditor
= nullptr;
1559 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1561 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1562 qreal dpr
= qApp
->devicePixelRatio();
1563 if (scene() && !scene()->views().isEmpty()) {
1564 dpr
= scene()->views().constFirst()->devicePixelRatioF();
1569 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1570 % ":" % QString::number(mode
);
1573 if (!QPixmapCache::find(key
, &pixmap
)) {
1574 QIcon icon
= QIcon::fromTheme(name
);
1575 if (icon
.isNull()) {
1578 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1579 icon
= fallbackIcon
;
1582 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1583 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1584 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1587 // Strangely KFileItem::overlays() returns empty string-values, so
1588 // we need to check first whether an overlay must be drawn at all.
1589 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1590 // assumes that an overlay will be drawn and has some additional
1592 for (const QString
&overlay
: overlays
) {
1593 if (!overlay
.isEmpty()) {
1594 int state
= KIconLoader::DefaultState
;
1600 state
= KIconLoader::ActiveState
;
1602 case QIcon::Disabled
:
1603 state
= KIconLoader::DisabledState
;
1605 case QIcon::Selected
:
1606 state
= KIconLoader::SelectedState
;
1610 // There is at least one overlay, draw all overlays above m_pixmap
1611 // and cancel the check
1612 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1617 QPixmapCache::insert(key
, pixmap
);
1619 pixmap
.setDevicePixelRatio(dpr
);
1624 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1626 const qreal height
= option
.fontMetrics
.ascent();
1627 return QSizeF(height
* 5, height
);
1630 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1632 return option
.padding
* 6;
1635 #include "moc_kstandarditemlistwidget.cpp"