QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgscolorswatchgrid.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscolorswatchgrid.cpp
3 ------------------
4 Date : July 2014
5 Copyright : (C) 2014 by Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgscolorswatchgrid.h"
17#include "moc_qgscolorswatchgrid.cpp"
18#include "qgsapplication.h"
19#include "qgssymbollayerutils.h"
20#include "qgscolortooltip_p.h"
21#include <QPainter>
22#include <QMouseEvent>
23#include <QMenu>
24#include <QBuffer>
25
26#define NUMBER_COLORS_PER_ROW 10 //number of color swatches per row
27
28QgsColorSwatchGrid::QgsColorSwatchGrid( QgsColorScheme *scheme, const QString &context, QWidget *parent )
29 : QWidget( parent )
30 , mScheme( scheme )
31 , mContext( context )
32 , mDrawBoxDepressed( false )
33 , mCurrentHoverBox( -1 )
34 , mFocused( false )
35 , mCurrentFocusBox( 0 )
36 , mPressedOnWidget( false )
37{
38 //need to receive all mouse over events
39 setMouseTracking( true );
40
41 setFocusPolicy( Qt::StrongFocus );
42 setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
43
44 mLabelHeight = Qgis::UI_SCALE_FACTOR * fontMetrics().height();
45 mLabelMargin = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( '.' );
46 mSwatchSize = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 1.75;
47 mSwatchOutlineSize = std::max( fontMetrics().horizontalAdvance( '.' ) * 0.4, 1.0 );
48
49 mSwatchSpacing = mSwatchSize * 0.3;
50 mSwatchMargin = mLabelMargin;
51
52 //calculate widget width
53 mWidth = NUMBER_COLORS_PER_ROW * mSwatchSize + ( NUMBER_COLORS_PER_ROW - 1 ) * mSwatchSpacing + mSwatchMargin + mSwatchMargin;
54
56}
57
59{
60 return QSize( mWidth, calculateHeight() );
61}
62
64{
65 return QSize( mWidth, calculateHeight() );
66}
67
68void QgsColorSwatchGrid::setContext( const QString &context )
69{
70 mContext = context;
72}
73
74void QgsColorSwatchGrid::setBaseColor( const QColor &baseColor )
75{
76 mBaseColor = baseColor;
78}
79
81{
82 //get colors from scheme
83 mColors = mScheme->fetchColors( mContext, mBaseColor );
84
85 //have to update size of widget in case number of colors has changed
86 updateGeometry();
87 repaint();
88}
89
90void QgsColorSwatchGrid::paintEvent( QPaintEvent *event )
91{
92 Q_UNUSED( event )
93 QPainter painter( this );
94 draw( painter );
95 painter.end();
96}
97
98void QgsColorSwatchGrid::mouseMoveEvent( QMouseEvent *event )
99{
100 //calculate box mouse cursor is over
101 const int newBox = swatchForPosition( event->pos() );
102
103 mDrawBoxDepressed = event->buttons() & Qt::LeftButton;
104 if ( newBox != mCurrentHoverBox )
105 {
106 //only repaint if changes are required
107 mCurrentHoverBox = newBox;
108 repaint();
109
110 updateTooltip( newBox );
111 }
112
113 emit hovered();
114}
115
116void QgsColorSwatchGrid::updateTooltip( const int colorIdx )
117{
118 if ( colorIdx >= 0 && colorIdx < mColors.length() )
119 {
120 const QColor color = mColors.at( colorIdx ).first;
121
122 //if color has an associated name from the color scheme, use that
123 const QString colorName = mColors.at( colorIdx ).second;
124
125 QString info;
126 if ( !colorName.isEmpty() )
127 info += QStringLiteral( "<h3>%1</h3><p>" ).arg( colorName );
128
129 info += QgsColorTooltip::htmlDescription( color, this );
130
131 setToolTip( info );
132
133 }
134 else
135 {
136 //clear tooltip
137 setToolTip( QString() );
138 }
139}
140
141void QgsColorSwatchGrid::mousePressEvent( QMouseEvent *event )
142{
143 if ( !mDrawBoxDepressed && event->buttons() & Qt::LeftButton )
144 {
145 mCurrentHoverBox = swatchForPosition( event->pos() );
146 mDrawBoxDepressed = true;
147 repaint();
148 }
149 mPressedOnWidget = true;
150}
151
153{
154 if ( ! mPressedOnWidget )
155 {
156 return;
157 }
158
159 const int box = swatchForPosition( event->pos() );
160 if ( mDrawBoxDepressed && event->button() == Qt::LeftButton )
161 {
162 mCurrentHoverBox = box;
163 mDrawBoxDepressed = false;
164 repaint();
165 }
166
167 if ( box >= 0 && box < mColors.length() && event->button() == Qt::LeftButton )
168 {
169 //color clicked
170 emit colorChanged( mColors.at( box ).first );
171 }
172}
173
174void QgsColorSwatchGrid::keyPressEvent( QKeyEvent *event )
175{
176 //handle keyboard navigation
177 if ( event->key() == Qt::Key_Right )
178 {
179 mCurrentFocusBox = std::min< int >( mCurrentFocusBox + 1, mColors.length() - 1 );
180 }
181 else if ( event->key() == Qt::Key_Left )
182 {
183 mCurrentFocusBox = std::max< int >( mCurrentFocusBox - 1, 0 );
184 }
185 else if ( event->key() == Qt::Key_Up )
186 {
187 int currentRow = mCurrentFocusBox / NUMBER_COLORS_PER_ROW;
188 const int currentColumn = mCurrentFocusBox % NUMBER_COLORS_PER_ROW;
189 currentRow--;
190
191 if ( currentRow >= 0 )
192 {
193 mCurrentFocusBox = currentRow * NUMBER_COLORS_PER_ROW + currentColumn;
194 }
195 else
196 {
197 //moved above first row
198 focusPreviousChild();
199 }
200 }
201 else if ( event->key() == Qt::Key_Down )
202 {
203 int currentRow = mCurrentFocusBox / NUMBER_COLORS_PER_ROW;
204 const int currentColumn = mCurrentFocusBox % NUMBER_COLORS_PER_ROW;
205 currentRow++;
206 const int box = currentRow * NUMBER_COLORS_PER_ROW + currentColumn;
207
208 if ( box < mColors.length() )
209 {
210 mCurrentFocusBox = box;
211 }
212 else
213 {
214 //moved below first row
215 focusNextChild();
216 }
217 }
218 else if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Space )
219 {
220 //color clicked
221 emit colorChanged( mColors.at( mCurrentFocusBox ).first );
222 }
223 else
224 {
225 //some other key, pass it on
226 QWidget::keyPressEvent( event );
227 return;
228 }
229
230 repaint();
231}
232
233void QgsColorSwatchGrid::focusInEvent( QFocusEvent *event )
234{
235 Q_UNUSED( event )
236 mFocused = true;
237 repaint();
238}
239
240void QgsColorSwatchGrid::focusOutEvent( QFocusEvent *event )
241{
242 Q_UNUSED( event )
243 mFocused = false;
244 repaint();
245}
246
247int QgsColorSwatchGrid::calculateHeight() const
248{
249 const int numberRows = std::ceil( static_cast<double>( mColors.length() ) / NUMBER_COLORS_PER_ROW );
250 return numberRows * ( mSwatchSize ) + ( numberRows - 1 ) * mSwatchSpacing + mSwatchMargin + mLabelHeight + 0.5 * mLabelMargin + mSwatchMargin;
251}
252
253void QgsColorSwatchGrid::draw( QPainter &painter )
254{
255 const QPalette pal = QPalette( qApp->palette() );
256 const QColor headerBgColor = pal.color( QPalette::Mid );
257 const QColor headerTextColor = pal.color( QPalette::BrightText );
258 const QColor highlight = pal.color( QPalette::Highlight );
259
260 //draw header background
261 painter.setBrush( headerBgColor );
262 painter.setPen( Qt::NoPen );
263 painter.drawRect( QRect( 0, 0, width(), mLabelHeight + 0.5 * mLabelMargin ) );
264
265 //draw header text
266 painter.setPen( headerTextColor );
267 painter.drawText( QRect( mLabelMargin, 0.25 * mLabelMargin, width() - 2 * mLabelMargin, mLabelHeight ),
268 Qt::AlignLeft | Qt::AlignVCenter, mScheme->schemeName() );
269
270 //draw color swatches
271 QgsNamedColorList::const_iterator colorIt = mColors.constBegin();
272 int index = 0;
273 for ( ; colorIt != mColors.constEnd(); ++colorIt )
274 {
275 const int row = index / NUMBER_COLORS_PER_ROW;
276 const int column = index % NUMBER_COLORS_PER_ROW;
277
278 QRect swatchRect = QRect( column * ( mSwatchSize + mSwatchSpacing ) + mSwatchMargin,
279 row * ( mSwatchSize + mSwatchSpacing ) + mSwatchMargin + mLabelHeight + 0.5 * mLabelMargin,
280 mSwatchSize, mSwatchSize );
281
282 if ( mCurrentHoverBox == index )
283 {
284 //hovered boxes are slightly larger
285 swatchRect.adjust( -1, -1, 1, 1 );
286 }
287
288 //start with checkboard pattern for semi-transparent colors
289 if ( ( *colorIt ).first.alpha() != 255 )
290 {
291 const QBrush checkBrush = QBrush( transparentBackground() );
292 painter.setPen( Qt::NoPen );
293 painter.setBrush( checkBrush );
294 painter.drawRect( swatchRect );
295 }
296
297 if ( mCurrentHoverBox == index )
298 {
299 if ( mDrawBoxDepressed )
300 {
301 painter.setPen( QPen( QColor( 100, 100, 100 ), mSwatchOutlineSize ) );
302 }
303 else
304 {
305 //hover color
306 painter.setPen( QPen( QColor( 220, 220, 220 ), mSwatchOutlineSize ) );
307 }
308 }
309 else if ( mFocused && index == mCurrentFocusBox )
310 {
311 painter.setPen( highlight );
312 }
313 else if ( ( *colorIt ).first.name() == mBaseColor.name() )
314 {
315 //currently active color
316 painter.setPen( QPen( QColor( 75, 75, 75 ), mSwatchOutlineSize ) );
317 }
318 else
319 {
320 painter.setPen( QPen( QColor( 197, 197, 197 ), mSwatchOutlineSize ) );
321 }
322
323 painter.setBrush( ( *colorIt ).first );
324 painter.drawRect( swatchRect );
325
326 index++;
327 }
328}
329
330QPixmap QgsColorSwatchGrid::transparentBackground()
331{
332 static QPixmap sTranspBkgrd;
333
334 if ( sTranspBkgrd.isNull() )
335 sTranspBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) );
336
337 return sTranspBkgrd;
338}
339
340int QgsColorSwatchGrid::swatchForPosition( QPoint position ) const
341{
342 //calculate box for position
343 int box = -1;
344 const int column = ( position.x() - mSwatchMargin ) / ( mSwatchSize + mSwatchSpacing );
345 const int xRem = ( position.x() - mSwatchMargin ) % ( mSwatchSize + mSwatchSpacing );
346 const int row = ( position.y() - mSwatchMargin - mLabelHeight ) / ( mSwatchSize + mSwatchSpacing );
347 const int yRem = ( position.y() - mSwatchMargin - mLabelHeight ) % ( mSwatchSize + mSwatchSpacing );
348
349 if ( xRem <= mSwatchSize + 1 && yRem <= mSwatchSize + 1 && column < NUMBER_COLORS_PER_ROW )
350 {
351 //if pos is actually inside a valid box, calculate which box
352 box = column + row * NUMBER_COLORS_PER_ROW;
353 }
354 return box;
355}
356
357
358//
359// QgsColorGridAction
360//
361
362
363QgsColorSwatchGridAction::QgsColorSwatchGridAction( QgsColorScheme *scheme, QMenu *menu, const QString &context, QWidget *parent )
364 : QWidgetAction( parent )
365 , mMenu( menu )
366 , mSuppressRecurse( false )
367 , mDismissOnColorSelection( true )
368{
369 mColorSwatchGrid = new QgsColorSwatchGrid( scheme, context, parent );
370
371 setDefaultWidget( mColorSwatchGrid );
372 connect( mColorSwatchGrid, &QgsColorSwatchGrid::colorChanged, this, &QgsColorSwatchGridAction::setColor );
373
374 connect( this, &QAction::hovered, this, &QgsColorSwatchGridAction::onHover );
375 connect( mColorSwatchGrid, &QgsColorSwatchGrid::hovered, this, &QgsColorSwatchGridAction::onHover );
376
377 //hide the action if no colors to be shown
378 setVisible( !mColorSwatchGrid->colors()->isEmpty() );
379}
380
381void QgsColorSwatchGridAction::setBaseColor( const QColor &baseColor )
382{
383 mColorSwatchGrid->setBaseColor( baseColor );
384}
385
387{
388 return mColorSwatchGrid->baseColor();
389}
390
392{
393 return mColorSwatchGrid->context();
394}
395
396void QgsColorSwatchGridAction::setContext( const QString &context )
397{
398 mColorSwatchGrid->setContext( context );
399}
400
402{
403 mColorSwatchGrid->refreshColors();
404 //hide the action if no colors shown
405 setVisible( !mColorSwatchGrid->colors()->isEmpty() );
406}
407
408void QgsColorSwatchGridAction::setColor( const QColor &color )
409{
410 emit colorChanged( color );
411 QAction::trigger();
412 if ( mMenu && mDismissOnColorSelection )
413 {
414 mMenu->hide();
415 }
416}
417
418void QgsColorSwatchGridAction::onHover()
419{
420 //see https://bugreports.qt.io/browse/QTBUG-10427?focusedCommentId=185610&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-185610
421
422 if ( mSuppressRecurse )
423 {
424 return;
425 }
426
427 if ( mMenu )
428 {
429 mSuppressRecurse = true;
430 mMenu->setActiveAction( this );
431 mSuppressRecurse = false;
432 }
433}
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition qgis.h:5667
static QPixmap getThemePixmap(const QString &name, const QColor &foreColor=QColor(), const QColor &backColor=QColor(), int size=16)
Helper to get a theme icon as a pixmap.
Abstract base class for color schemes.
virtual QString schemeName() const =0
Gets the name for the color scheme.
virtual QgsNamedColorList fetchColors(const QString &context=QString(), const QColor &baseColor=QColor())=0
Gets a list of colors from the scheme.
void setBaseColor(const QColor &baseColor)
Sets the base color for the color grid.
QString context() const
Gets the current context for the color grid.
void colorChanged(const QColor &color)
Emitted when a color has been selected from the widget.
QgsColorSwatchGridAction(QgsColorScheme *scheme, QMenu *menu=nullptr, const QString &context=QString(), QWidget *parent=nullptr)
Construct a new color swatch grid action.
void refreshColors()
Reload colors from scheme and redraws the widget.
QColor baseColor() const
Gets the base color for the color grid.
void setContext(const QString &context)
Sets the current context for the color grid.
A grid of color swatches, which allows for user selection.
void mouseMoveEvent(QMouseEvent *event) override
void mousePressEvent(QMouseEvent *event) override
QColor baseColor() const
Gets the base color for the widget.
QgsColorSwatchGrid(QgsColorScheme *scheme, const QString &context=QString(), QWidget *parent=nullptr)
Construct a new color swatch grid.
void paintEvent(QPaintEvent *event) override
QgsNamedColorList * colors()
Gets the list of colors shown in the grid.
void colorChanged(const QColor &color)
Emitted when a color has been selected from the widget.
void setBaseColor(const QColor &baseColor)
Sets the base color for the widget.
QSize minimumSizeHint() const override
void mouseReleaseEvent(QMouseEvent *event) override
QSize sizeHint() const override
void refreshColors()
Reload colors from scheme and redraws the widget.
void focusInEvent(QFocusEvent *event) override
void keyPressEvent(QKeyEvent *event) override
void focusOutEvent(QFocusEvent *event) override
void hovered()
Emitted when mouse hovers over widget.
void setContext(const QString &context)
Sets the current context for the grid.
QString context() const
Gets the current context for the grid.
static QString htmlDescription(QColor color, T *widget)
Returns an HTML desciption given a color with a preview image of the color.
#define NUMBER_COLORS_PER_ROW