QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsfontbutton.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsfontbutton.h
3 ---------------
4 Date : May 2017
5 Copyright : (C) 2017 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 "qgsfontbutton.h"
17
18#include "qgsapplication.h"
19#include "qgscolorscheme.h"
21#include "qgscolorswatchgrid.h"
22#include "qgscolorwidgets.h"
23#include "qgsdoublespinbox.h"
25#include "qgsfontutils.h"
26#include "qgsmapcanvas.h"
27#include "qgsmenuheader.h"
28#include "qgsscreenhelper.h"
29#include "qgssymbollayerutils.h"
30#include "qgstextformatwidget.h"
31#include "qgstextrenderer.h"
32#include "qgsunittypes.h"
33#include "qgsvectorlayer.h"
34
35#include <QClipboard>
36#include <QDrag>
37#include <QMenu>
38#include <QString>
39#include <QToolTip>
40
41#include "moc_qgsfontbutton.cpp"
42
43using namespace Qt::StringLiterals;
44
45QgsFontButton::QgsFontButton( QWidget *parent, const QString &dialogTitle )
46 : QToolButton( parent )
47 , mDialogTitle( dialogTitle.isEmpty() ? tr( "Text Format" ) : dialogTitle )
48 , mNullFormatString( tr( "No Format" ) )
49{
50 setText( tr( "Font" ) );
51
52 setAcceptDrops( true );
53 connect( this, &QAbstractButton::clicked, this, &QgsFontButton::showSettingsDialog );
54
55 //setup dropdown menu
56 mMenu = new QMenu( this );
57 connect( mMenu, &QMenu::aboutToShow, this, &QgsFontButton::prepareMenu );
58 setMenu( mMenu );
59 setPopupMode( QToolButton::MenuButtonPopup );
60
61 //make sure height of button looks good under different platforms
62 const QSize size = QToolButton::minimumSizeHint();
63 const int fontHeight = Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 1.4;
64 const int minWidth = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 20;
65 mSizeHint = QSize( std::max( minWidth, size.width() ), std::max( size.height(), fontHeight ) );
66
67 mScreenHelper = new QgsScreenHelper( this );
68 connect( mScreenHelper, &QgsScreenHelper::screenDpiChanged, this, [this] { updatePreview(); } );
69}
70
72{
73 return mSizeHint;
74}
75
77{
78 return mSizeHint;
79}
80
81void QgsFontButton::showSettingsDialog()
82{
83 switch ( mMode )
84 {
86 {
88 if ( mExpressionContextGenerator )
89 context = mExpressionContextGenerator->createExpressionContext();
90 else
91 {
93 }
94
95 QgsSymbolWidgetContext symbolContext;
96 symbolContext.setExpressionContext( &context );
97 symbolContext.setMapCanvas( mMapCanvas );
98 symbolContext.setMessageBar( mMessageBar );
99
100 QgsPanelWidget *panel = QgsPanelWidget::findParentPanel( this );
101 if ( panel && panel->dockMode() )
102 {
103 mActivePanel = new QgsTextFormatPanelWidget( mFormat, mMapCanvas, this, mLayer.data() );
104 mActivePanel->setPanelTitle( mDialogTitle );
105 mActivePanel->setContext( symbolContext );
106
107 connect( mActivePanel, &QgsTextFormatPanelWidget::changed, this, [this] {
108 setTextFormat( mActivePanel->format() );
109 QgsFontUtils::addRecentFontFamily( mActivePanel->format().font().family() );
110 } );
111 panel->openPanel( mActivePanel );
112 return;
113 }
114
115 QgsTextFormatDialog dialog( mFormat, mMapCanvas, this, QgsGuiUtils::ModalDialogFlags, mLayer.data() );
116 dialog.setWindowTitle( mDialogTitle );
117 dialog.setContext( symbolContext );
118 if ( dialog.exec() )
119 {
120 setTextFormat( dialog.format() );
121 QgsFontUtils::addRecentFontFamily( mFormat.font().family() );
122 }
123 break;
124 }
125
126 case ModeQFont:
127 {
128 bool ok;
129 const QFont newFont = QgsGuiUtils::getFont( ok, mFont, mDialogTitle );
130 if ( ok )
131 {
132 QgsFontUtils::addRecentFontFamily( newFont.family() );
133 setCurrentFont( newFont );
134 }
135 break;
136 }
137 }
138
139 // reactivate button's window
140 activateWindow();
141 raise();
142}
143
145{
146 return mMapCanvas;
147}
148
150{
151 mMapCanvas = mapCanvas;
152}
153
155{
156 mMessageBar = bar;
157}
158
160{
161 return mMessageBar;
162}
163
165{
166 if ( mActivePanel && !format.isValid() )
167 mActivePanel->acceptPanel();
168
169 mFormat = format;
170 updatePreview();
171
172 if ( mActivePanel && format.isValid() )
173 mActivePanel->setFormat( format );
174 emit changed();
175}
176
178{
179 mFormat = QgsTextFormat();
180 updatePreview();
181 emit changed();
182}
183
184void QgsFontButton::setColor( const QColor &color )
185{
186 QColor opaque = color;
187 opaque.setAlphaF( 1.0 );
188
189 if ( mNullFormatAction )
190 mNullFormatAction->setChecked( false );
191
192 if ( mFormat.color() != opaque )
193 {
194 mFormat.setColor( opaque );
195 updatePreview();
196 emit changed();
197 }
198}
199
201{
202 switch ( mMode )
203 {
204 case ModeTextRenderer:
205 QApplication::clipboard()->setMimeData( mFormat.toMimeData().release() );
206 break;
207
208 case ModeQFont:
209 QApplication::clipboard()->setMimeData( QgsFontUtils::toMimeData( mFont ).release() );
210 break;
211 }
212}
213
215{
216 QgsTextFormat tempFormat;
217 QFont font;
218 if ( mMode == ModeTextRenderer && formatFromMimeData( QApplication::clipboard()->mimeData(), tempFormat ) )
219 {
220 setTextFormat( tempFormat );
221 QgsFontUtils::addRecentFontFamily( mFormat.font().family() );
222 }
223 else if ( mMode == ModeQFont && fontFromMimeData( QApplication::clipboard()->mimeData(), font ) )
224 {
225 QgsFontUtils::addRecentFontFamily( font.family() );
226 setCurrentFont( font );
227 }
228}
229
230bool QgsFontButton::event( QEvent *e )
231{
232 if ( e->type() == QEvent::ToolTip )
233 {
234 QHelpEvent *helpEvent = static_cast<QHelpEvent *>( e );
235 QString toolTip;
236 double fontSize = 0.0;
237 switch ( mMode )
238 {
239 case ModeTextRenderer:
240 fontSize = mFormat.size();
241 break;
242
243 case ModeQFont:
244 fontSize = mFont.pointSizeF();
245 break;
246 }
247 toolTip = u"<b>%1</b><br>%2<br>Size: %3"_s.arg( text(), mMode == ModeTextRenderer ? mFormat.font().family() : mFont.family() ).arg( fontSize );
248 QToolTip::showText( helpEvent->globalPos(), toolTip );
249 }
250 return QToolButton::event( e );
251}
252
253void QgsFontButton::mousePressEvent( QMouseEvent *e )
254{
255 if ( e->button() == Qt::LeftButton )
256 {
257 mDragStartPosition = e->pos();
258 }
259 QToolButton::mousePressEvent( e );
260}
261
262void QgsFontButton::contextMenuEvent( QContextMenuEvent *e )
263{
264 QToolButton::showMenu();
265 e->accept();
266}
267
268void QgsFontButton::mouseMoveEvent( QMouseEvent *e )
269{
270 //handle dragging fonts from button
271
272 if ( !( e->buttons() & Qt::LeftButton ) )
273 {
274 //left button not depressed, so not a drag
275 QToolButton::mouseMoveEvent( e );
276 return;
277 }
278
279 if ( ( e->pos() - mDragStartPosition ).manhattanLength() < QApplication::startDragDistance() )
280 {
281 //mouse not moved, so not a drag
282 QToolButton::mouseMoveEvent( e );
283 return;
284 }
285
286 //user is dragging font
287 QDrag *drag = new QDrag( this );
288 switch ( mMode )
289 {
290 case ModeTextRenderer:
291 drag->setMimeData( mFormat.toMimeData().release() );
292 break;
293
294 case ModeQFont:
295 drag->setMimeData( QgsFontUtils::toMimeData( mFont ).release() );
296 break;
297 }
298 const int iconSize = QgsGuiUtils::scaleIconSize( 50 );
299 drag->setPixmap( createDragIcon( QSize( iconSize, iconSize ) ) );
300 drag->exec( Qt::CopyAction );
301 setDown( false );
302}
303
304bool QgsFontButton::colorFromMimeData( const QMimeData *mimeData, QColor &resultColor, bool &hasAlpha )
305{
306 hasAlpha = false;
307 const QColor mimeColor = QgsSymbolLayerUtils::colorFromMimeData( mimeData, hasAlpha );
308
309 if ( mimeColor.isValid() )
310 {
311 resultColor = mimeColor;
312 return true;
313 }
314
315 //could not get color from mime data
316 return false;
317}
318
319void QgsFontButton::dragEnterEvent( QDragEnterEvent *e )
320{
321 //is dragged data valid font data?
322 QColor mimeColor;
323 QgsTextFormat format;
324 QFont font;
325 bool hasAlpha = false;
326
327 if ( mMode == ModeTextRenderer && formatFromMimeData( e->mimeData(), format ) )
328 {
329 e->acceptProposedAction();
330 updatePreview( QColor(), &format );
331 }
332 else if ( mMode == ModeQFont && fontFromMimeData( e->mimeData(), font ) )
333 {
334 e->acceptProposedAction();
335 updatePreview( QColor(), nullptr, &font );
336 }
337 else if ( mMode == ModeTextRenderer && colorFromMimeData( e->mimeData(), mimeColor, hasAlpha ) )
338 {
339 //if so, we accept the drag, and temporarily change the button's color
340 //to match the dragged color. This gives immediate feedback to the user
341 //that colors can be dropped here
342 e->acceptProposedAction();
343 updatePreview( mimeColor );
344 }
345}
346
347void QgsFontButton::dragLeaveEvent( QDragLeaveEvent *e )
348{
349 Q_UNUSED( e )
350 //reset button color
351 updatePreview();
352}
353
354void QgsFontButton::dropEvent( QDropEvent *e )
355{
356 //is dropped data valid format data?
357 QColor mimeColor;
358 QgsTextFormat format;
359 QFont font;
360 bool hasAlpha = false;
361 if ( mMode == ModeTextRenderer && formatFromMimeData( e->mimeData(), format ) )
362 {
363 setTextFormat( format );
364 QgsFontUtils::addRecentFontFamily( mFormat.font().family() );
365 return;
366 }
367 else if ( mMode == ModeQFont && fontFromMimeData( e->mimeData(), font ) )
368 {
369 QgsFontUtils::addRecentFontFamily( font.family() );
370 setCurrentFont( font );
371 return;
372 }
373 else if ( mMode == ModeTextRenderer && colorFromMimeData( e->mimeData(), mimeColor, hasAlpha ) )
374 {
375 //accept drop and set new color
376 e->acceptProposedAction();
377
378 if ( hasAlpha )
379 {
380 mFormat.setOpacity( mimeColor.alphaF() );
381 }
382 mimeColor.setAlphaF( 1.0 );
383 mFormat.setColor( mimeColor );
385 updatePreview();
386 emit changed();
387 }
388 updatePreview();
389}
390
392{
393 double size = 0;
394 switch ( mMode )
395 {
396 case ModeTextRenderer:
397 size = mFormat.size();
398 break;
399
400 case ModeQFont:
401 size = mFont.pointSizeF();
402 break;
403 }
404
405 const double increment = ( event->modifiers() & Qt::ControlModifier ) ? 0.1 : 1;
406 if ( event->angleDelta().y() > 0 )
407 {
408 size += increment;
409 }
410 else
411 {
412 size -= increment;
413 }
414 size = std::max( size, 1.0 );
415
416 switch ( mMode )
417 {
418 case ModeTextRenderer:
419 {
420 QgsTextFormat newFormat = mFormat;
421 newFormat.setSize( size );
422 setTextFormat( newFormat );
423 break;
424 }
425
426 case ModeQFont:
427 {
428 QFont newFont = mFont;
429 newFont.setPointSizeF( size );
430 setCurrentFont( newFont );
431 break;
432 }
433 }
434
435 event->accept();
436}
437
438QPixmap QgsFontButton::createColorIcon( const QColor &color ) const
439{
440 //create an icon pixmap
441 const int iconSize = QgsGuiUtils::scaleIconSize( 16 );
442 QPixmap pixmap( iconSize, iconSize );
443 pixmap.fill( Qt::transparent );
444
445 QPainter p;
446 p.begin( &pixmap );
447
448 //draw color over pattern
449 p.setBrush( QBrush( color ) );
450
451 //draw border
452 p.setPen( QColor( 197, 197, 197 ) );
453 p.drawRect( 0, 0, iconSize - 1, iconSize - 1 );
454 p.end();
455 return pixmap;
456}
457
458QPixmap QgsFontButton::createDragIcon( QSize size, const QgsTextFormat *tempFormat, const QFont *tempFont ) const
459{
460 if ( !tempFormat )
461 tempFormat = &mFormat;
462 if ( !tempFont )
463 tempFont = &mFont;
464
465 //create an icon pixmap
466 QPixmap pixmap( size.width(), size.height() );
467 pixmap.fill( Qt::transparent );
468 QPainter p;
469 p.begin( &pixmap );
470 p.setRenderHint( QPainter::Antialiasing );
471 const QRect rect( 0, 0, size.width(), size.height() );
472
473 if ( mMode == ModeQFont || tempFormat->color().lightnessF() < 0.7 )
474 {
475 p.setBrush( QBrush( QColor( 255, 255, 255 ) ) );
476 p.setPen( QPen( QColor( 150, 150, 150 ), 0 ) );
477 }
478 else
479 {
480 p.setBrush( QBrush( QColor( 0, 0, 0 ) ) );
481 p.setPen( QPen( QColor( 100, 100, 100 ), 0 ) );
482 }
483 p.drawRect( rect );
484 p.setBrush( Qt::NoBrush );
485 p.setPen( Qt::NoPen );
486
487 switch ( mMode )
488 {
489 case ModeTextRenderer:
490 {
491 QgsRenderContext context;
492 QgsMapToPixel newCoordXForm;
493 newCoordXForm.setParameters( 1, 0, 0, 0, 0, 0 );
494 context.setMapToPixel( newCoordXForm );
495
496 context.setScaleFactor( mScreenHelper->screenDpi() / 25.4 );
498 context.setPainter( &p );
499
500 // slightly inset text to account for buffer/background
501 const double fontSize = context.convertToPainterUnits( tempFormat->size(), tempFormat->sizeUnit(), tempFormat->sizeMapUnitScale() );
502 double xtrans = 0;
503 if ( tempFormat->buffer().enabled() )
504 xtrans = tempFormat->buffer().sizeUnit() == Qgis::RenderUnit::Percentage
505 ? fontSize * tempFormat->buffer().size() / 100
506 : context.convertToPainterUnits( tempFormat->buffer().size(), tempFormat->buffer().sizeUnit(), tempFormat->buffer().sizeMapUnitScale() );
507 if ( tempFormat->background().enabled() && tempFormat->background().sizeType() != QgsTextBackgroundSettings::SizeFixed )
508 xtrans = std::max( xtrans, context.convertToPainterUnits( tempFormat->background().size().width(), tempFormat->background().sizeUnit(), tempFormat->background().sizeMapUnitScale() ) );
509
510 double ytrans = 0.0;
511 if ( tempFormat->buffer().enabled() )
512 ytrans = std::max(
513 ytrans,
515 ? fontSize * tempFormat->buffer().size() / 100
516 : context.convertToPainterUnits( tempFormat->buffer().size(), tempFormat->buffer().sizeUnit(), tempFormat->buffer().sizeMapUnitScale() )
517 );
518 if ( tempFormat->background().enabled() )
519 ytrans = std::max( ytrans, context.convertToPainterUnits( tempFormat->background().size().height(), tempFormat->background().sizeUnit(), tempFormat->background().sizeMapUnitScale() ) );
520
521 QRectF textRect = rect;
522 textRect.setLeft( xtrans );
523 textRect.setWidth( textRect.width() - xtrans );
524 textRect.setTop( ytrans );
525 if ( textRect.height() > 300 )
526 textRect.setHeight( 300 );
527 if ( textRect.width() > 2000 )
528 textRect.setWidth( 2000 );
529
530 QgsTextRenderer::drawText( textRect, 0, Qgis::TextHorizontalAlignment::Center, QStringList() << tr( "Aa" ), context, *tempFormat );
531 break;
532 }
533 case ModeQFont:
534 {
535 p.setBrush( Qt::NoBrush );
536 p.setPen( QColor( 0, 0, 0 ) );
537 p.setFont( *tempFont );
538 QRectF textRect = rect;
539 textRect.setLeft( 2 );
540 p.drawText( textRect, Qt::AlignVCenter, tr( "Aa" ) );
541 break;
542 }
543 }
544
545 p.end();
546 return pixmap;
547}
548
549void QgsFontButton::prepareMenu()
550{
551 //we need to tear down and rebuild this menu every time it is shown. Otherwise the space allocated to any
552 //QgsColorSwatchGridAction is not recalculated by Qt and the swatch grid may not be the correct size
553 //for the number of colors shown in the grid. Note that we MUST refresh color swatch grids every time this
554 //menu is opened, otherwise color schemes like the recent color scheme grid are meaningless
555 mMenu->clear();
556
557 if ( mMode == ModeTextRenderer && mShowNoFormat )
558 {
559 mNullFormatAction = new QAction( mNullFormatString, this );
560 mMenu->addAction( mNullFormatAction );
561 connect( mNullFormatAction, &QAction::triggered, this, &QgsFontButton::setToNullFormat );
562 if ( !mFormat.isValid() )
563 {
564 mNullFormatAction->setCheckable( true );
565 mNullFormatAction->setChecked( true );
566 }
567 }
568
569 QWidgetAction *sizeAction = new QWidgetAction( mMenu );
570 QWidget *sizeWidget = new QWidget();
571 QVBoxLayout *sizeLayout = new QVBoxLayout();
572 sizeLayout->setContentsMargins( 0, 0, 0, 3 );
573 sizeLayout->setSpacing( 2 );
574
575 QString fontHeaderLabel;
576 switch ( mMode )
577 {
578 case ModeTextRenderer:
579 fontHeaderLabel = tr( "Font size (%1)" ).arg( QgsUnitTypes::toString( mFormat.sizeUnit() ) );
580 break;
581
582 case ModeQFont:
583 fontHeaderLabel = tr( "Font size (pt)" );
584 break;
585 }
586
587 QgsMenuHeader *sizeLabel = new QgsMenuHeader( fontHeaderLabel );
588 sizeLayout->addWidget( sizeLabel );
589
590 QgsDoubleSpinBox *sizeSpin = new QgsDoubleSpinBox( nullptr );
591 sizeSpin->setDecimals( 4 );
592 sizeSpin->setMaximum( 1e+9 );
593 sizeSpin->setShowClearButton( false );
594 sizeSpin->setValue( mMode == ModeTextRenderer ? mFormat.size() : mFont.pointSizeF() );
595 connect( sizeSpin, static_cast<void ( QgsDoubleSpinBox::* )( double )>( &QgsDoubleSpinBox::valueChanged ), this, [this]( double value ) {
596 switch ( mMode )
597 {
598 case ModeTextRenderer:
599 if ( mNullFormatAction )
600 mNullFormatAction->setChecked( false );
601 mFormat.setSize( value );
602 break;
603 case ModeQFont:
604 mFont.setPointSizeF( value );
605 break;
606 }
607 updatePreview();
608 emit changed();
609 } );
610 QHBoxLayout *spinLayout = new QHBoxLayout();
611 spinLayout->setContentsMargins( 4, 0, 4, 0 );
612 spinLayout->addWidget( sizeSpin );
613 sizeLayout->addLayout( spinLayout );
614 sizeWidget->setLayout( sizeLayout );
615 sizeAction->setDefaultWidget( sizeWidget );
616 sizeWidget->setFocusProxy( sizeSpin );
617 sizeWidget->setFocusPolicy( Qt::StrongFocus );
618 mMenu->addAction( sizeAction );
619
620 QMenu *recentFontMenu = new QMenu( tr( "Recent Fonts" ), mMenu );
621 const auto recentFontFamilies { QgsFontUtils::recentFontFamilies() };
622 for ( const QString &family : recentFontFamilies )
623 {
624 QAction *fontAction = new QAction( family, recentFontMenu );
625 QFont f = fontAction->font();
626 QgsFontUtils::setFontFamily( f, family );
627 fontAction->setFont( f );
628 fontAction->setToolTip( family );
629 recentFontMenu->addAction( fontAction );
630 if ( ( mMode == ModeTextRenderer && family == mFormat.font().family() ) || ( mMode == ModeQFont && family == mFont.family() ) )
631 {
632 fontAction->setCheckable( true );
633 fontAction->setChecked( true );
634 }
635 auto setFont = [this, family] {
636 switch ( mMode )
637 {
638 case ModeTextRenderer:
639 {
640 QgsTextFormat newFormat = mFormat;
641 QFont f = newFormat.font();
642 QgsFontUtils::setFontFamily( f, family );
643 newFormat.setFont( f );
644 setTextFormat( newFormat );
645 QgsFontUtils::addRecentFontFamily( mFormat.font().family() );
646 break;
647 }
648 case ModeQFont:
649 {
650 QFont font = mFont;
651 QgsFontUtils::setFontFamily( font, family );
652 setCurrentFont( font );
654 break;
655 }
656 }
657 };
658 connect( fontAction, &QAction::triggered, this, setFont );
659 }
660 mMenu->addMenu( recentFontMenu );
661
662 QAction *configureAction = new QAction( tr( "Configure Format…" ), this );
663 mMenu->addAction( configureAction );
664 connect( configureAction, &QAction::triggered, this, &QgsFontButton::showSettingsDialog );
665
666 QAction *copyFormatAction = new QAction( tr( "Copy Format" ), this );
667 mMenu->addAction( copyFormatAction );
668 connect( copyFormatAction, &QAction::triggered, this, &QgsFontButton::copyFormat );
669 QAction *pasteFormatAction = new QAction( tr( "Paste Format" ), this );
670 //enable or disable paste action based on current clipboard contents. We always show the paste
671 //action, even if it's disabled, to give hint to the user that pasting colors is possible
672 QgsTextFormat tempFormat;
673 QFont tempFont;
674 const int iconSize = QgsGuiUtils::scaleIconSize( 16 );
675 if ( mMode == ModeTextRenderer && formatFromMimeData( QApplication::clipboard()->mimeData(), tempFormat ) )
676 {
678 tempFormat.setSize( 14 );
679 pasteFormatAction->setIcon( createDragIcon( QSize( iconSize, iconSize ), &tempFormat ) );
680 }
681 else if ( mMode == ModeQFont && fontFromMimeData( QApplication::clipboard()->mimeData(), tempFont ) )
682 {
683 tempFont.setPointSize( 8 );
684 pasteFormatAction->setIcon( createDragIcon( QSize( iconSize, iconSize ), nullptr, &tempFont ) );
685 }
686 else
687 {
688 pasteFormatAction->setEnabled( false );
689 }
690 mMenu->addAction( pasteFormatAction );
691 connect( pasteFormatAction, &QAction::triggered, this, &QgsFontButton::pasteFormat );
692
693 if ( mMode == ModeTextRenderer )
694 {
695 mMenu->addSeparator();
696
697 QgsColorWheel *colorWheel = new QgsColorWheel( mMenu );
698 colorWheel->setColor( mFormat.color() );
699 QgsColorWidgetAction *colorAction = new QgsColorWidgetAction( colorWheel, mMenu, mMenu );
700 colorAction->setDismissOnColorSelection( false );
701 connect( colorAction, &QgsColorWidgetAction::colorChanged, this, &QgsFontButton::setColor );
702 mMenu->addAction( colorAction );
703
704 QgsColorRampWidget *alphaRamp = new QgsColorRampWidget( mMenu, QgsColorWidget::Alpha, QgsColorRampWidget::Horizontal );
705 QColor alphaColor = mFormat.color();
706 alphaColor.setAlphaF( mFormat.opacity() );
707 alphaRamp->setColor( alphaColor );
708 QgsColorWidgetAction *alphaAction = new QgsColorWidgetAction( alphaRamp, mMenu, mMenu );
709 alphaAction->setDismissOnColorSelection( false );
710 connect( alphaAction, &QgsColorWidgetAction::colorChanged, this, [this]( const QColor &color ) {
711 const double opacity = color.alphaF();
712 mFormat.setOpacity( opacity );
713 updatePreview();
714 if ( mNullFormatAction )
715 mNullFormatAction->setChecked( false );
716 emit changed();
717 } );
718 connect( colorAction, &QgsColorWidgetAction::colorChanged, alphaRamp, [alphaRamp]( const QColor &color ) { alphaRamp->setColor( color, false ); } );
719 mMenu->addAction( alphaAction );
720
721 //get schemes with ShowInColorButtonMenu flag set
723 QList<QgsColorScheme *>::iterator it = schemeList.begin();
724 for ( ; it != schemeList.end(); ++it )
725 {
726 QgsColorSwatchGridAction *colorAction = new QgsColorSwatchGridAction( *it, mMenu, u"labeling"_s, this );
727 colorAction->setBaseColor( mFormat.color() );
728 mMenu->addAction( colorAction );
730 connect( colorAction, &QgsColorSwatchGridAction::colorChanged, this, &QgsFontButton::addRecentColor );
731 }
732
733 mMenu->addSeparator();
734
735 QAction *copyColorAction = new QAction( tr( "Copy Color" ), this );
736 mMenu->addAction( copyColorAction );
737 connect( copyColorAction, &QAction::triggered, this, &QgsFontButton::copyColor );
738
739 QAction *pasteColorAction = new QAction( tr( "Paste Color" ), this );
740 //enable or disable paste action based on current clipboard contents. We always show the paste
741 //action, even if it's disabled, to give hint to the user that pasting colors is possible
742 QColor clipColor;
743 bool hasAlpha = false;
744 if ( colorFromMimeData( QApplication::clipboard()->mimeData(), clipColor, hasAlpha ) )
745 {
746 pasteColorAction->setIcon( createColorIcon( clipColor ) );
747 }
748 else
749 {
750 pasteColorAction->setEnabled( false );
751 }
752 mMenu->addAction( pasteColorAction );
753 connect( pasteColorAction, &QAction::triggered, this, &QgsFontButton::pasteColor );
754 }
755}
756
757void QgsFontButton::addRecentColor( const QColor &color )
758{
760}
761
763{
764 return mFont;
765}
766
768{
769 return mLayer;
770}
771
773{
774 mLayer = layer;
775}
776
778{
779 mExpressionContextGenerator = generator;
780}
781
782void QgsFontButton::setCurrentFont( const QFont &font )
783{
784 mFont = font;
785 updatePreview();
786 emit changed();
787}
788
790{
791 return mMode;
792}
793
795{
796 mMode = mode;
797 updatePreview();
798}
799
800bool QgsFontButton::formatFromMimeData( const QMimeData *mimeData, QgsTextFormat &resultFormat ) const
801{
802 if ( !mimeData )
803 return false;
804
805 bool ok = false;
806 resultFormat = QgsTextFormat::fromMimeData( mimeData, &ok );
807 return ok;
808}
809
810bool QgsFontButton::fontFromMimeData( const QMimeData *mimeData, QFont &resultFont ) const
811{
812 if ( !mimeData )
813 return false;
814
815 bool ok = false;
816 resultFont = QgsFontUtils::fromMimeData( mimeData, &ok );
817 return ok;
818}
819
821{
822 if ( e->type() == QEvent::EnabledChange )
823 {
824 updatePreview();
825 }
826 QToolButton::changeEvent( e );
827}
828
829void QgsFontButton::showEvent( QShowEvent *e )
830{
831 updatePreview();
832 QToolButton::showEvent( e );
833}
834
836{
837 QToolButton::resizeEvent( event );
838 //recalculate icon size and redraw icon
839 mIconSize = QSize();
840 updatePreview();
841}
842
843void QgsFontButton::updatePreview( const QColor &color, QgsTextFormat *format, QFont *font )
844{
845 if ( mShowNoFormat && !mFormat.isValid() )
846 {
847 setIcon( QPixmap() );
848 return;
849 }
850
851 QgsTextFormat tempFormat;
852 QFont tempFont;
853
854 if ( format )
855 tempFormat = *format;
856 else
857 tempFormat = mFormat;
858 if ( font )
859 tempFont = *font;
860 else
861 tempFont = mFont;
862
863 if ( color.isValid() )
864 tempFormat.setColor( color );
865
866 // always show font previews based on the standard font size for buttons. Otherwise large/small text
867 // will be unreadable, making the button very non-user-friendly.
868 // Note that we take away a few points here, as the text in these buttons is rendered with a fairly large
869 // margin and we'd like to avoid cropping the text.
870 tempFormat.setSize( QToolButton::font().pointSizeF() - 2 );
872
873 QSize currentIconSize;
874 //icon size is button size with a small margin
875 if ( menu() )
876 {
877 if ( !mIconSize.isValid() )
878 {
879 //calculate size of push button part of widget (ie, without the menu dropdown button part)
880 QStyleOptionToolButton opt;
881 initStyleOption( &opt );
882 const QRect buttonSize = QApplication::style()->subControlRect( QStyle::CC_ToolButton, &opt, QStyle::SC_ToolButton, this );
883 //make sure height of icon looks good under different platforms
884#ifdef Q_OS_WIN
885 mIconSize = QSize( buttonSize.width() - 10, height() - 6 );
886#elif defined( Q_OS_MAC )
887 mIconSize = QSize( buttonSize.width() - 10, height() - 2 );
888#else
889 mIconSize = QSize( buttonSize.width() - 10, height() - 12 );
890#endif
891 }
892 currentIconSize = mIconSize;
893 }
894 else
895 {
896 //no menu
897#ifdef Q_OS_WIN
898 currentIconSize = QSize( width() - 10, height() - 6 );
899#else
900 currentIconSize = QSize( width() - 10, height() - 12 );
901#endif
902 }
903
904 if ( !currentIconSize.isValid() || currentIconSize.width() <= 0 || currentIconSize.height() <= 0 )
905 {
906 return;
907 }
908
909 //create an icon pixmap
910 QPixmap pixmap( currentIconSize * devicePixelRatioF() );
911 pixmap.fill( Qt::transparent );
912 pixmap.setDevicePixelRatio( devicePixelRatioF() );
913 QPainter p;
914 p.begin( &pixmap );
915 p.setRenderHint( QPainter::Antialiasing );
916 const QRect rect( 0, 0, currentIconSize.width(), currentIconSize.height() );
917
918 switch ( mMode )
919 {
920 case ModeTextRenderer:
921 {
922 QgsRenderContext context;
923 QgsMapToPixel newCoordXForm;
924 newCoordXForm.setParameters( 1, 0, 0, 0, 0, 0 );
925 context.setMapToPixel( newCoordXForm );
926
927 context.setScaleFactor( mScreenHelper->screenDpi() / 25.4 );
928 context.setDevicePixelRatio( devicePixelRatioF() );
931 context.setPainter( &p );
932
933 // slightly inset text to account for buffer/background
934 const double fontSize = context.convertToPainterUnits( tempFormat.size(), tempFormat.sizeUnit(), tempFormat.sizeMapUnitScale() );
935 double xtrans = 0;
936 if ( tempFormat.buffer().enabled() )
937 xtrans = tempFormat.buffer().sizeUnit() == Qgis::RenderUnit::Percentage
938 ? fontSize * tempFormat.buffer().size() / 100
939 : context.convertToPainterUnits( tempFormat.buffer().size(), tempFormat.buffer().sizeUnit(), tempFormat.buffer().sizeMapUnitScale() );
940 if ( tempFormat.background().enabled() && tempFormat.background().sizeType() != QgsTextBackgroundSettings::SizeFixed )
941 xtrans = std::max( xtrans, context.convertToPainterUnits( tempFormat.background().size().width(), tempFormat.background().sizeUnit(), tempFormat.background().sizeMapUnitScale() ) );
942
943 double ytrans = 0.0;
944 if ( tempFormat.buffer().enabled() )
945 ytrans = std::max(
946 ytrans,
948 ? fontSize * tempFormat.buffer().size() / 100
949 : context.convertToPainterUnits( tempFormat.buffer().size(), tempFormat.buffer().sizeUnit(), tempFormat.buffer().sizeMapUnitScale() )
950 );
951 if ( tempFormat.background().enabled() )
952 ytrans = std::max( ytrans, context.convertToPainterUnits( tempFormat.background().size().height(), tempFormat.background().sizeUnit(), tempFormat.background().sizeMapUnitScale() ) );
953
954 QRectF textRect = rect;
955 textRect.setLeft( xtrans );
956 textRect.setWidth( textRect.width() - xtrans );
957 textRect.setTop( ytrans );
958 if ( textRect.height() > 300 )
959 textRect.setHeight( 300 );
960 if ( textRect.width() > 2000 )
961 textRect.setWidth( 2000 );
962
963 QgsTextRenderer::drawText( textRect, 0, Qgis::TextHorizontalAlignment::Left, QStringList() << text(), context, tempFormat );
964 break;
965 }
966 case ModeQFont:
967 {
968 p.setBrush( Qt::NoBrush );
969 p.setPen( QColor( 0, 0, 0 ) );
970 p.setFont( tempFont );
971 QRectF textRect = rect;
972 textRect.setLeft( 2 );
973 p.drawText( textRect, Qt::AlignVCenter, text() );
974 break;
975 }
976 }
977 p.end();
978 setIconSize( currentIconSize );
979 setIcon( pixmap );
980}
981
983{
984 //copy color
985 QApplication::clipboard()->setMimeData( QgsSymbolLayerUtils::colorToMimeData( mFormat.color() ).release() );
986}
987
989{
990 QColor clipColor;
991 bool hasAlpha = false;
992 if ( colorFromMimeData( QApplication::clipboard()->mimeData(), clipColor, hasAlpha ) )
993 {
994 //paste color
995 setColor( clipColor );
997 }
998}
999
1000void QgsFontButton::setDialogTitle( const QString &title )
1001{
1002 mDialogTitle = title;
1003}
1004
1006{
1007 return mDialogTitle;
1008}
@ PreferVector
Prefer vector-based rendering, when the result will still be visually near-identical to a raster-base...
Definition qgis.h:2918
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
Definition qgis.h:5774
@ Points
Points (e.g., for font sizes).
Definition qgis.h:5775
@ Pixels
Pixels.
Definition qgis.h:5773
@ Antialiasing
Use antialiasing while drawing.
Definition qgis.h:2984
@ Center
Center align.
Definition qgis.h:3181
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition qgis.h:7405
static QgsColorSchemeRegistry * colorSchemeRegistry()
Returns the application's color scheme registry, used for managing color schemes.
@ Horizontal
Horizontal ramp.
QList< QgsColorScheme * > schemes() const
Returns all color schemes in the registry.
@ ShowInColorButtonMenu
Show scheme in color button drop-down menu.
void setBaseColor(const QColor &baseColor)
Sets the base color for the color grid.
void colorChanged(const QColor &color)
Emitted when a color has been selected from the widget.
void setColor(const QColor &color, bool emitSignals=false) override
void setDismissOnColorSelection(bool dismiss)
Sets whether the parent menu should be dismissed and closed when a color is selected from the action'...
void colorChanged(const QColor &color)
Emitted when a color has been selected from the widget.
virtual void setColor(const QColor &color, bool emitSignals=false)
Sets the color for the widget.
@ Alpha
Alpha component (opacity) of color.
void setShowClearButton(bool showClearButton)
Sets whether the widget will show a clear button.
Abstract interface for generating an expression context.
virtual QgsExpressionContext createExpressionContext() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
static std::vector< std::unique_ptr< QgsExpressionContextScope > > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
void copyColor()
Copies the current text color to the clipboard.
QgsMapCanvas * mapCanvas() const
Returns the map canvas associated with the widget.
void pasteColor()
Pastes a color from the clipboard to the text format.
QSize sizeHint() const override
void setToNullFormat()
Sets the text format to a null (invalid) QgsTextFormat.
void setMapCanvas(QgsMapCanvas *canvas)
Sets a map canvas to associate with the widget.
void setMessageBar(QgsMessageBar *bar)
Sets the message bar associated with the widget.
QgsMessageBar * messageBar() const
Returns the message bar associated with the widget.
void contextMenuEvent(QContextMenuEvent *e) override
Mode
Available button modes.
@ ModeQFont
Configure font settings for use with QFont objects.
@ ModeTextRenderer
Configure font settings for use with QgsTextRenderer.
QString dialogTitle
void setCurrentFont(const QFont &font)
Sets the current text font to show in the widget.
void mousePressEvent(QMouseEvent *e) override
QgsVectorLayer * layer() const
Returns the layer associated with the widget.
void setLayer(QgsVectorLayer *layer)
Sets a layer to associate with the widget.
QSize minimumSizeHint() const override
void mouseMoveEvent(QMouseEvent *e) override
QgsFontButton(QWidget *parent=nullptr, const QString &dialogTitle=QString())
Construct a new font button.
void changeEvent(QEvent *e) override
void changed()
Emitted when the widget's text format settings are changed.
void resizeEvent(QResizeEvent *event) override
void registerExpressionContextGenerator(QgsExpressionContextGenerator *generator)
Register an expression context generator class that will be used to retrieve an expression context fo...
void dragEnterEvent(QDragEnterEvent *e) override
void dragLeaveEvent(QDragLeaveEvent *e) override
void setColor(const QColor &color)
Sets the current color for the text.
void pasteFormat()
Pastes a format from the clipboard.
void showEvent(QShowEvent *e) override
void setDialogTitle(const QString &title)
Sets the title for the text settings dialog window.
void wheelEvent(QWheelEvent *event) override
bool event(QEvent *e) override
void dropEvent(QDropEvent *e) override
void setTextFormat(const QgsTextFormat &format)
Sets the current text format to show in the widget.
void copyFormat()
Copies the current text format to the clipboard.
void setMode(Mode mode)
Sets the current button mode.
static std::unique_ptr< QMimeData > toMimeData(const QFont &font)
Returns new mime data representing the specified font settings.
static void setFontFamily(QFont &font, const QString &family)
Sets the family for a font object.
static void addRecentFontFamily(const QString &family)
Adds a font family to the list of recently used font families.
static QFont fromMimeData(const QMimeData *data, bool *ok=nullptr)
Attempts to parse the provided mime data as a QFont.
static QStringList recentFontFamilies()
Returns a list of recently used font families.
Map canvas is a class for displaying all GIS data types on a canvas.
void setParameters(double mapUnitsPerPixel, double centerX, double centerY, int widthPixels, int heightPixels, double rotation)
Sets parameters for use in transforming coordinates.
A bar for displaying non-blocking messages to the user.
void openPanel(QgsPanelWidget *panel)
Open a panel or dialog depending on dock mode setting If dock mode is true this method will emit the ...
bool dockMode() const
Returns the dock mode state.
void changed()
Emitted when the widget state changes.
static QgsPanelWidget * findParentPanel(QWidget *widget)
Traces through the parents of a widget to find if it is contained within a QgsPanelWidget widget.
static void addRecentColor(const QColor &color)
Adds a color to the list of recent colors.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
void setDevicePixelRatio(float ratio)
Sets the device pixel ratio.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
void setRasterizedRenderingPolicy(Qgis::RasterizedRenderingPolicy policy)
Sets the policy controlling when rasterisation of content during renders is permitted.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
A utility class for dynamic handling of changes to screen properties.
void screenDpiChanged(double dpi)
Emitted whenever the screen dpi associated with the widget is changed.
static QColor colorFromMimeData(const QMimeData *data, bool &hasAlpha)
Attempts to parse mime data as a color.
static std::unique_ptr< QMimeData > colorToMimeData(const QColor &color)
Creates mime data from a color.
void setMapCanvas(QgsMapCanvas *canvas)
Sets the map canvas associated with the widget.
void setMessageBar(QgsMessageBar *bar)
Sets the message bar associated with the widget.
void setExpressionContext(QgsExpressionContext *context)
Sets the optional expression context used for the widget.
QSizeF size() const
Returns the size of the background shape.
bool enabled() const
Returns whether the background is enabled.
SizeType sizeType() const
Returns the method used to determine the size of the background shape (e.g., fixed size or buffer aro...
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the shape size.
Qgis::RenderUnit sizeUnit() const
Returns the units used for the shape's size.
Qgis::RenderUnit sizeUnit() const
Returns the units for the buffer size.
double size() const
Returns the size of the buffer.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the buffer size.
bool enabled() const
Returns whether the buffer is enabled.
Container for all settings relating to text rendering.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setSize(double size)
Sets the size for rendered text.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the size.
void setFont(const QFont &font)
Sets the font used for rendering text.
static QgsTextFormat fromMimeData(const QMimeData *data, bool *ok=nullptr)
Attempts to parse the provided mime data as a QgsTextFormat.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units for the size of rendered text.
bool isValid() const
Returns true if the format is valid.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
Qgis::RenderUnit sizeUnit() const
Returns the units for the size of rendered text.
double size() const
Returns the size for rendered text.
QColor color() const
Returns the color that text will be rendered in.
QFont font() const
Returns the font used for rendering text.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
static void drawText(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true, Qgis::TextVerticalAlignment vAlignment=Qgis::TextVerticalAlignment::Top, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle)
Draws text within a rectangle using the specified settings.
static Q_INVOKABLE QString toString(Qgis::DistanceUnit unit)
Returns a translated string representing a distance unit.
Represents a vector layer which manages a vector based dataset.
int scaleIconSize(int standardSize)
Scales an icon size to compensate for display pixel density, making the icon size hi-dpi friendly,...
QFont getFont(bool &ok, const QFont &initial, const QString &title)
Show font selection dialog.