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