Referência para a classe QPainter

A classe QPainter executa pinturas de baixo nível em widgets e outros dispositivos de pintura. Ele fornece funções altamente otimizadas para fazer a maior parte dos desenhos que os programas gráficos necessitam. Pode desenhar quase tudo de linhas simples a formas complexas como tortas e cordas. Pode também desenhar texto alinhado e pixmaps. Normalmente,  ele desenha um sistema de coordenadas “natural”, mas também pode visualizar e transformar objetos. O QPainter pode operar em qualquer objeto derivado da classe QPaintDevice.

O uso comum do QPainter é dentro do evento paint de um widget: Construir e personalizar (ex.: ajuste da caneta ou pincel) o painter. Em seguida fazer o desenho. Lembre de destruir o objeto QPainter após o desenho. Exemplo:

 void SimpleExampleWidget::paintEvent(QPaintEvent *)
 {
     QPainter painter(this);
     painter.setPen(Qt::blue);
     painter.setFont(QFont("Arial", 30));
     painter.drawText(rect(), Qt::AlignCenter, "Qt");
 }

A funcionalidade principal do QPainter é desenho, mas a classe fornece também várias funcionalidades que permitem a personalização dos ajustes do QPainter e a qualidade da renderização, e também permitem ativar o clipping. Além disso, você pode controlar como formas diferentes serão desenhas juntas pela especificação do modo de composição do painter.

A função isActive() indica se o painter está ativo. Um painter é ativado pela função begin() e o construtor que usa um argumento QPaintDevice. A função end(), e o destrutor, desativam ele.

Junto com as classes QPaintDevice e QPaintEngine, o QPainter forma a base para o sistema de pintura do Qt. O QPainter é  a classe usada para executar operações de desenho. QPaintDevice representa um dispositivo que pode ser pintado usando um QPainter. QPaintEngine fornece a interface que o painter usa para desenhar em tipos diferentes de dispositivos. Se o painter está ativo, o device() retorna o dispositivo de pintura onde o painter atua, e paintEngine() retorna o mecanismo de pntura que o painter está utilizando.

Algumas vezes é desejável fazer alguma pintura em um QPaintDevice não usual. O QPainter suporta uma função  estática para fazer isso, setRedirected().

Aviso: Quando o dispositivo de pintura é um widget, o QPainter pode apenas ser usado dentro de função paintEvent() ou em uma função chamada por paintEvent(); isso a menos que o atributo Qt::WA_PaintOutsidePaintEvent do widget esteja configurado. No MacOSX e Windows, você pode desenhar o widget apenas na função paintEvent() não importando se o atributo esta ativo ou não.

Configurações

Existem várias configurações que você pode personalizar para fazer com que o QPainter faça o desenho de acordo com suas preferências:

  • font() é a fonte usada para o desenho do texto. Se o painter estiver isActive(), você pode recuperar as informações sobre a fonte atualmente configurada, suas métricas, usando as funções fontInfo() respectivamente.
  • brush() define as cores ou padrões que são usados para preencher as formas.
  • pen() define a cor ou risco que é usado para desenhar linhas ou bordas.
  • backgroundMode() define quando haverá um background() ou não, isso é, se  o fundo será Qt::OpaqueMode ou Qt::TransparentMode.
  • background() apenas se aplica quando backgroundMode() for Qt::OpaqueMode e pen() é um risco. Nesse caso, descreve a cor dos pixels do fundo.
  • brushOrigin() define a origem dos pinceis de azulejos, normalmente a origem do fundo do widget.
  • viewport(), window(), worldMatrix() cria o sistema de transformação de coordenadas do painter.
  • hasClipping() informa se o painter será recortado. Em caso positivo, ele será recortado na região definida por clipRegion().
  • layoutDirection() define a direção do layout usada pelo painter quando desenhar o texto.
  • matrixEnabled() informa se a transformação do mundo está ativada.
  • viewTransformEnabled() informa se a transformação do view está ativada.

Observe que alguns dessas configurações espelham configurações em alguns dispositivos, ex.: QWidget::font(). A função QPainter::begin() (ou de forma equivalente o construtor do QPainter) copia esses atributos do dispositivo de pintura.

Você pode a qualquer momento salvar o estado do QPainter chamando a função save() que salva todas as configurações disponíveis em uma pilha interna. A função restore() recupera esses dados.

Funções de Desenho

O QPainter fornece funções para desenhar várias primitivas: drawPoint(), drawPoints(), drawLine(), drawRect(), drawRoundedRect(), drawEllipse(), drawArc(), drawPie(), drawChord(), drawPolyline(), drawPolygon(), drawConvexPolygon() e drawCubicBezier(). As duas funções de conveniência, drawRects() e drawLines(), desenha um número dado de retângulos ou linhas em um array fornecido de  QRects or QLines usando a caneta e pincel atual.

A classe  QPainter fornece também a função  fillRect() que preenche o QRect, com o QBrush, e a função eraseRect() que apaga a área interna do retângulo passado.

Todas esses funções tem versões para inteiros e ponto flutuante.

 

Exemplo básico de desenho O Exemplo básico de desenho mostra como exibir gráficos primitivos em vários estilos suando a classe QPainter.

 

Se você precisa desenhar uma forma complexa, especialmente se precisa fazer isso repetifamente, considere criar um QPainterPath e desenhe usando drawPath().

 

Exemplo de desenho de caminhos A classe QPainterPath fornece um contêiner para operações de desenho,ativando formas gráficas para serem construídas e reutilizadas. O exemplo Painter Paths mostra como os caminhos de desenho podem ser usados para construir formas complexas.

 

O QPainter fornece tambpem a função fillPath() que preenche um QPainterPath dado com um QBrush, e a função strokePath() que desenha o contorno do caminho informado (isto é, traceja o caminho).

Veja também o exemplo Vector Deformation que mostra como usar técnicas de vetorização avançadas para desenhar texto usando QPainterPath, o exemplo Gradients que mostra os diferentes tipos de gradientes que estão disponíveis no Qt, e o exemplo Path Stroking que mostra padrões de traços do Qt e mostra como padrões personalizados pode ser suados para estender a faixa de padrões disponíveis.

 

Vector Deformation Gradients Path Stroking

 

Existem funções para desenhar pixmaps/imagens, nomeadas como drawPixmap(), drawImage() e drawTiledPixmap(). Tanto drawPixmap() quanto drawImage() produzem o mesmo resultado, exceto que drawPixmap() é mais rápida na tela enquanto drawImage() é mais rápida quando usando uma QPrinter ou outros dispositivos.

Desenho de texto é feito usando a função drawText(). Quando você precisar de um ajuste fino do posicionamento, a função boundingRect() informa onde um comando drawText() será desenhado.

Existe uma função drawPicture() que desenha o conteúdo de uma imagem em QPicture. A função drawPicture() é a única  função que não leva em consideração as configurações do painter pois tem as suas próprias configurações.

Qualidade de renderização

Para obter o melhor resultado de renderização usando o QPainter, você deve usar a plataforma independente QImage como dispositivo de pintura; isto é, usando QImage irpa garantir que você terá uma representação de pixel idêntica em qualquer plataforma.

A classe QPainter fornece também uma maneira de controlar a qualidade da renderização através do enum  RenderHint e do suporte a precisão em ponto flutuante: Todas as funções para desenho de primtiivas tem uma versão em ponto flutuante. Essas funções são usadas frequentemente em combinação com  QPainter::Antialiasing.

 

Exemplo de círculos concêntricos O exemplo Concentric Circles mostra a qualidade aperfeiçoada de renderização que pode ser obtida usando precisão de ponto flutuante e anti-aliasing quando estiver desenhando widgets personalizados que são desenhados usando várias combinações de precisão e  anti-aliasing.

 

O enum RenderHint especifica as flags que podem ou não ser respeitadas em uma dado mecanismos pelo QPainter. QPainter::Antialiasing indica que o mecanismo deve usar anti-aliasing nas primitivas se possível, QPainter::TextAntialiasing indica que o mecanismos deve usar anti-aliasing no texto se possível, e  QPainter::SmoothPixmapTransform indica que o mecanismo deve usar um algoritmo de suavização da transformação de pixmaps. HighQualityAntialiasing é uma renderização especifica para OpenGL que indica que o mecanismo deve usar fragmentos de programas e renderização fora da tela para anti-aliasing.

A função renderHints() retorna uma flag que especifica quais dicas de renderização estão configuradas para o painter. Use a função  setRenderHint() para ajustar ou limpar os RenderHints atualmente configurados.

Transformações de coordenadas

Normalmente, o QPainter opera no próprio sistema de coordenadas do dispositivo (usualmente pixels), mas o QPainter tem um bom suporte para transformação de coordenadas.

 

nop rotate() scale() translate()

 

As transformações mais usadas são escalonamento, rotação, traslação e cisalhamento. Use a função scale() para escalonar o sistema de coordenadas em um determinado intervalo, a função rotate() gira no sentido horário e translate() translada o objeto (isto é, adiciona um deslocamento aos pontos). Você pode também torcer o sistema de coordenadas em volta de um ponto de origem usando a função shear(). Veja o exemplo Affine Transformations para visualização de um sistema de coordenadas torcido.

See also the Transformations example which shows how transformations influence the way that QPainter renders graphics primitives. In particular it shows how the order of transformations affects the result.

 

Exemplo de Transformações afins O exemplo Affine Transformations mostra a habilidade do Qt de executar transformações em operações de desenho. O exemplo também permite ao usuário fazer experimentos com as operações de transformação e ver os resultados de imediato.

 

Todas as operações de transformação executam suas ações na  worldMatrix(). Uma matriz transforma um ponto em um plano em outro plano.

A função setWorldMatrix() pode substituir ou adicionar uma worldMatrix() atualmente configurada. A função resetMatrix() reinicia qualquer transformação que foi feita usando as funções translate(), scale(), shear(), rotate(), setWorldMatrix(), setViewport() e setWindow(). A função deviceMatrix() retorna a matriz que transforma coordenadas lógicas em coordenadas do dispositivos da plataforma do desenho. A última função é necessária apenas quando estiverem sendo usados comandos de desenho da plataforma com um manipulador dependente da plataforma, e a plataforma não faz as transformações nativamente.

Quando estiver desenhando com o QPainter, especificamentos os pontos usando coordenadas lógicas que são convertidas em coordenadas físicas do dispositivo. O mapeamento das coordenadas lógicas para coordenadas físicas é feito pela função  combinedMatrix() do QPainter, uma combinação de viewport() e window() e worldMatrix(). O viewport() representa as coordenadas físicas que especificam um retângulo arbitrário, window() descrive o mesmo retângulo em coordenadas lógicas, e worldMatrix() é idêntico a matriz de transformação.

Recorte ( Clipping )

O QPainter pode recortar qualquer operação de desenho em um retângulo, uma região, ou um caminho vetorial. O corte está disponível usando as funções clipRegion() e clipPath(). A melhor  (ou mais rápida) escolha, caminhos ou regiões, depende do paintEngine() subjacente. Por exemplo, para o  QImage é preferível usar caminhos enquanto o X11 prefere regiões. Configurar um recorte é feito pelo painter através de coordenadas lógicas.

Depois do recorte do QPainter, o dispositivo pode também fazer um recorte. Por exemplo, muitos widgets cortam pixels usados pelo seus filhos, e muitas impressoras cortam áreas próximas aos cantos do papel. Esse recorte adicional não reflete o valor de retorno de clipRegion() ou hasClipping().

Modos de composição

O QPainter fornece o enum CompositionMode que define as regras de Porter-Duff para composição de imagem digital; ele descreve um modelo para combinação de pixels em uma imagem, a fonte, com pixels em outra imagem, o destino.

As duas formas mais comuns de composição são Source e SourceOverSource é usada para desenhar objetos opacos em um dispositivo. Nesse modo, cada pixel da fonte substitui o correspondente pixel no destino. No modo de composição SourceOver, o objeto da origem é transparente e é desenhado sobre o destino.

Note que a transformação de composições opera baseado nos pixels. Por essa razão, existe uma diferença entre a primitiva gráfica e o retângulo que o envolve: O retângulo contém pixels com alpha == 0 (isto é, pixels circunjacentes a primitiva). Esses pixels irão sobrescrever os outros pixels da imagem, afetivamente limpando estes, enquanto a primitiva apenas sobrescreve a sua própria área.

 

Exemplo de modos de composição O exemplo Composition Modes, disponível no diretório de exemplos do Qt, permite que você faça experimentos com vários modos de composição e veja os resultados de imediato.

 

Documentação dos tipos

enum QPainter::CompositionMode

Defines the modes supported for digital image compositing. Composition modes are used to specify how the pixels in one image, the source, are merged with the pixel in another image, the destination.

Please note that the bitwise raster operation modes, denoted with a RasterOp prefix, are only natively supported in the X11 and raster paint engines. This means that the only way to utilize these modes on the Mac is via a QImage. The RasterOp denoted blend modes are not supported for pens and brushes with alpha components. Also, turning on the QPainter::Antialiasing render hint will effectively disable the RasterOp modes.

The most common type is SourceOver (often referred to as just alpha blending) where the source pixel is blended on top of the destination pixel in such a way that the alpha component of the source defines the translucency of the pixel.

When the paint device is a QImage, the image format must be set to Format_ARGB32Premultiplied or Format_ARGB32 for the composition modes to have any effect. For performance the premultiplied version is the preferred format.

When a composition mode is set it applies to all painting operator, pens, brushes, gradients and pixmap/image drawing.

 

Constante Valores Descrição
QPainter::CompositionMode_SourceOver 0 This is the default mode. The alpha of the source is used to blend the pixel on top of the destination.
QPainter::CompositionMode_DestinationOver 1 The alpha of the destination is used to blend it on top of the source pixels. This mode is the inverse of CompositionMode_SourceOver.
QPainter::CompositionMode_Clear 2 The pixels in the destination are cleared (set to fully transparent) independent of the source.
QPainter::CompositionMode_Source 3 The output is the source pixel. (This means a basic copy operation and is identical to SourceOver when the source pixel is opaque).
QPainter::CompositionMode_Destination 4 The output is the destination pixel. This means that the blending has no effect. This mode is the inverse of CompositionMode_Source.
QPainter::CompositionMode_SourceIn 5 The output is the source, where the alpha is reduced by that of the destination.
QPainter::CompositionMode_DestinationIn 6 The output is the destination, where the alpha is reduced by that of the source. This mode is the inverse of CompositionMode_SourceIn.
QPainter::CompositionMode_SourceOut 7 The output is the source, where the alpha is reduced by the inverse of destination.
QPainter::CompositionMode_DestinationOut 8 The output is the destination, where the alpha is reduced by the inverse of the source. This mode is the inverse of CompositionMode_SourceOut.
QPainter::CompositionMode_SourceAtop 9 The source pixel is blended on top of the destination, with the alpha of the source pixel reduced by the alpha of the destination pixel.
QPainter::CompositionMode_DestinationAtop 10 The destination pixel is blended on top of the source, with the alpha of the destination pixel is reduced by the alpha of the destination pixel. This mode is the inverse of CompositionMode_SourceAtop.
QPainter::CompositionMode_Xor 11 The source, whose alpha is reduced with the inverse of the destination alpha, is merged with the destination, whose alpha is reduced by the inverse of the source alpha. CompositionMode_Xor is not the same as the bitwise Xor.
QPainter::CompositionMode_Plus 12 Both the alpha and color of the source and destination pixels are added together.
QPainter::CompositionMode_Multiply 13 The output is the source color multiplied by the destination. Multiplying a color with white leaves the color unchanged, while multiplying a color with black produces black.
QPainter::CompositionMode_Screen 14 The source and destination colors are inverted and then multiplied. Screening a color with white produces white, whereas screening a color with black leaves the color unchanged.
QPainter::CompositionMode_Overlay 15 Multiplies or screens the colors depending on the destination color. The destination color is mixed with the source color to reflect the lightness or darkness of the destination.
QPainter::CompositionMode_Darken 16 The darker of the source and destination colors is selected.
QPainter::CompositionMode_Lighten 17 The lighter of the source and destination colors is selected.
QPainter::CompositionMode_ColorDodge 18 The destination color is brightened to reflect the source color. A black source color leaves the destination color unchanged.
QPainter::CompositionMode_ColorBurn 19 The destination color is darkened to reflect the source color. A white source color leaves the destination color unchanged.
QPainter::CompositionMode_HardLight 20 Multiplies or screens the colors depending on the source color. A light source color will lighten the destination color, whereas a dark source color will darken the destination color.
QPainter::CompositionMode_SoftLight 21 Darkens or lightens the colors depending on the source color. Similar to CompositionMode_HardLight.
QPainter::CompositionMode_Difference 22 Subtracts the darker of the colors from the lighter. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.
QPainter::CompositionMode_Exclusion 23 Similar to CompositionMode_Difference, but with a lower contrast. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.
QPainter::RasterOp_SourceOrDestination 24 Does a bitwise OR operation on the source and destination pixels (src OR dst).
QPainter::RasterOp_SourceAndDestination 25 Does a bitwise AND operation on the source and destination pixels (src AND dst).
QPainter::RasterOp_SourceXorDestination 26 Does a bitwise XOR operation on the source and destination pixels (src XOR dst).
QPainter::RasterOp_NotSourceAndNotDestination 27 Does a bitwise NOR operation on the source and destination pixels ((NOT src) AND (NOT dst)).
QPainter::RasterOp_NotSourceOrNotDestination 28 Does a bitwise NAND operation on the source and destination pixels ((NOT src) OR (NOT dst)).
QPainter::RasterOp_NotSourceXorDestination 29 Does a bitwise operation where the source pixels are inverted and then XOR’ed with the destination ((NOT src) XOR dst).
QPainter::RasterOp_NotSource 30 Does a bitwise operation where the source pixels are inverted (NOT src).
QPainter::RasterOp_NotSourceAndDestination 31 Does a bitwise operation where the source is inverted and then AND’ed with the destination ((NOT src) AND dst).
QPainter::RasterOp_SourceAndNotDestination 32 Does a bitwise operation where the source is AND’ed with the inverted destination pixels (src AND (NOT dst)).

 

enum QPainter::RenderHint
flags QPainter::RenderHints

Renderhints are used to specify flags to QPainter that may or may not be respected by any given engine.

 

Constant Value Description
QPainter::Antialiasing 0x01 Indicates that the engine should antialias edges of primitives if possible.
QPainter::TextAntialiasing 0x02 Indicates that the engine should antialias text if possible. To forcibly disable antialiasing for text, do not use this hint. Instead, setQFont::NoAntialias on your font’s style strategy.
QPainter::SmoothPixmapTransform 0x04 Indicates that the engine should use a smooth pixmap transformation algorithm (such as bilinear) rather than nearest neighbor.
QPainter::HighQualityAntialiasing 0x08 An OpenGL-specific rendering hint indicating that the engine should use fragment programs and offscreen rendering for antialiasing.
QPainter::NonCosmeticDefaultPen 0x10 The engine should interpret pens with a width of 0 (which otherwise enables QPen::isCosmetic()) as being a non-cosmetic pen with a width of 1.

 

The RenderHints type is a typedef for QFlags<RenderHint>. It stores an OR combination of RenderHint values.


Documentação das funções membro

QPainter::QPainter ()

Constructs a painter.

QPainter::QPainter ( QPaintDevice * device )

Constructs a painter that begins painting the paint device immediately.

This constructor is convenient for short-lived painters, e.g. in a QWidget::paintEvent() and should be used only once. The constructor calls begin() for you and the QPainter destructor automatically calls end().

Here’s an example using begin() and end():

 void MyWidget::paintEvent(QPaintEvent *)
 {
     QPainter p;
     p.begin(this);
     p.drawLine(...);        // drawing code
     p.end();
 }

The same example using this constructor:

 void MyWidget::paintEvent(QPaintEvent *)
 {
     QPainter p(this);
     p.drawLine(...);        // drawing code
 }

Since the constructor cannot provide feedback when the initialization of the painter failed you should rather use begin() and end() to paint on external devices, e.g. printers.

QPainter::~QPainter ()

Destroys the painter.

const QBrush & QPainter::background () const

Returns the current background brush.

Qt::BGMode QPainter::backgroundMode () const

Returns the current background mode.

bool QPainter::begin ( QPaintDevice * device )

Begins painting the paint device and returns true if successful; otherwise returns false.

Notice that all painter settings (setPen(), setBrush() etc.) are reset to default values when begin() is called.

The errors that can occur are serious problems, such as these:

 painter->begin(0); // impossible - paint device cannot be 0

 QPixmap image(0, 0);
 painter->begin(&image); // impossible - image.isNull() == true;

 painter->begin(myWidget);
 painter2->begin(myWidget); // impossible - only one painter at a time

Note that most of the time, you can use one of the constructors instead of begin(), and that end() is automatically done at destruction.

Warning: A paint device can only be painted by one painter at a time.

QRectF QPainter::boundingRect ( const QRectF & rectangle, int flags, const QString & text )

Returns the bounding rectangle of the text as it will appear when drawn inside the given rectangle with the specified flags using the currently set font(); i.e the function tells you where the drawText() function will draw when given the same arguments.

If the text does not fit within the given rectangle using the specified flags, the function returns the required rectangle.

The flags argument is a bitwise OR of the following flags:

If several of the horizontal or several of the vertical alignment flags are set, the resulting alignment is undefined.

QRect QPainter::boundingRect ( const QRect & rectangle, int flags, const QString & text )

This is an overloaded function.

Returns the bounding rectangle of the text as it will appear when drawn inside the given rectangle with the specified flags using the currently set font().

QRect QPainter::boundingRect ( int x, int y, int w, int h, int flags, const QString & text )

This is an overloaded function.

Returns the bounding rectangle of the given text as it will appear when drawn inside the rectangle beginning at the point (xy) with width w and height h.

QRectF QPainter::boundingRect ( const QRectF & rectangle, const QString & text, const QTextOption & option = QTextOption() )

This is an overloaded function.

Instead of specifying flags as a bitwise OR of the Qt::AlignmentFlag and Qt::TextFlag, this overloaded function takes an option argument. The QTextOption class provides a description of general rich text properties.

See also QTextOption.

const QBrush & QPainter::brush () const

Returns the painter’s current brush.

QPoint QPainter::brushOrigin () const

Returns the currently set brush origin.

QPainterPath QPainter::clipPath () const

Returns the currently clip as a path. Note that the clip path is given in logical coordinates.

Warning: QPainter does not store the combined clip explicitly as this is handled by the underlying QPaintEngine, so the path is recreated on demand and transformed to the current logical coordinate system. This is potentially an expensive operation.

QRegion QPainter::clipRegion () const

Returns the currently set clip region. Note that the clip region is given in logical coordinates.

Warning: QPainter does not store the combined clip explicitly as this is handled by the underlying QPaintEngine, so the path is recreated on demand and transformed to the current logical coordinate system. This is potentially an expensive operation.

QMatrix QPainter::combinedMatrix () const

Returns the transformation matrix combining the current window/viewport and world transformation.

It is advisable to use combinedTransform() instead of this function to preserve the properties of perspective transformations.

QTransform QPainter::combinedTransform () const

Returns the transformation matrix combining the current window/viewport and world transformation.

CompositionMode QPainter::compositionMode () const

Returns the current composition mode.

QPaintDevice * QPainter::device () const

Returns the paint device on which this painter is currently painting, or 0 if the painter is not active.

const QMatrix & QPainter::deviceMatrix () const

Returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device.

Note: It is advisable to use deviceTransform() instead of this function to preserve the properties of perspective transformations.

This function is only needed when using platform painting commands on the platform dependent handle (Qt::HANDLE), and the platform does not do transformations nativly.

The QPaintEngine::PaintEngineFeature enum can be queried to determine whether the platform performs the transformations or not.

const QTransform & QPainter::deviceTransform () const

Returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device.

This function is only needed when using platform painting commands on the platform dependent handle (Qt::HANDLE), and the platform does not do transformations nativly.

The QPaintEngine::PaintEngineFeature enum can be queried to determine whether the platform performs the transformations or not.

void QPainter::drawArc ( const QRectF & rectangle, int startAngle, int spanAngle )

Draws the arc defined by the given rectanglestartAngle and spanAngle.

The startAngle and spanAngle must be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);
 int startAngle = 30 * 16;
 int spanAngle = 120 * 16;

 QPainter painter(this);
 painter.drawArc(rectangle, startAngle, spanAngle);

 

void QPainter::drawArc ( const QRect & rectangle, int startAngle, int spanAngle )

This is an overloaded function.

Draws the arc defined by the given rectanglestartAngle and spanAngle.

void QPainter::drawArc ( int x, int y, int width, int height, int startAngle, int spanAngle )

This is an overloaded function.

Draws the arc defined by the rectangle beginning at (xy) with the specified width and height, and the given startAngle and spanAngle.

void QPainter::drawChord ( const QRectF & rectangle, int startAngle, int spanAngle )

Draws the chord defined by the given rectanglestartAngle and spanAngle. The chord is filled with the current brush().

The startAngle and spanAngle must be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);
 int startAngle = 30 * 16;
 int spanAngle = 120 * 16;

 QPainter painter(this);
 painter.drawChord(rect, startAngle, spanAngle);

 

void QPainter::drawChord ( const QRect & rectangle, int startAngle, int spanAngle )

This is an overloaded function.

Draws the chord defined by the given rectanglestartAngle and spanAngle.

void QPainter::drawChord ( int x, int y, int width, int height, int startAngle, int spanAngle )

This is an overloaded function.

Draws the chord defined by the rectangle beginning at (xy) with the specified width and height, and the given startAngle and spanAngle.

void QPainter::drawConvexPolygon ( const QPointF * points, int pointCount )

Draws the convex polygon defined by the first pointCount points in the array points using the current pen.

 

 static const QPointF points[4] = {
     QPointF(10.0, 80.0),
     QPointF(20.0, 10.0),
     QPointF(80.0, 30.0),
     QPointF(90.0, 70.0)
 };

 QPainter painter(this);
 painter.drawConvexPolygon(points, 4);

 

The first point is implicitly connected to the last point, and the polygon is filled with the current brush(). If the supplied polygon is not convex, i.e. it contains at least one angle larger than 180 degrees, the results are undefined.

On some platforms (e.g. X11), the drawConvexPolygon() function can be faster than the drawPolygon() function.

void QPainter::drawConvexPolygon ( const QPoint * points, int pointCount )

This is an overloaded function.

Draws the convex polygon defined by the first pointCount points in the array points using the current pen.

void QPainter::drawConvexPolygon ( const QPolygonF & polygon )

This is an overloaded function.

Draws the convex polygon defined by polygon using the current pen and brush.

void QPainter::drawConvexPolygon ( const QPolygon & polygon )

This is an overloaded function.

Draws the convex polygon defined by polygon using the current pen and brush.

void QPainter::drawEllipse ( const QRectF & rectangle )

Draws the ellipse defined by the given rectangle.

A filled ellipse has a size of rectangle.size(). A stroked ellipse has a size of rectangle.size() plus the pen width.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);

 QPainter painter(this);
 painter.drawEllipse(rectangle);

 

See also drawPie() and The Coordinate System.

void QPainter::drawEllipse ( const QRect & rectangle )

This is an overloaded function.

Draws the ellipse defined by the given rectangle.

void QPainter::drawEllipse ( int x, int y, int width, int height )

This is an overloaded function.

Draws the ellipse defined by the rectangle beginning at (xy) with the given width and height.

void QPainter::drawEllipse ( const QPointF & centerqreal rxqreal ry )

This is an overloaded function.

Draws the ellipse positioned at center with radii rx and ry.

This function was introduced in Qt 4.4.

void QPainter::drawEllipse ( const QPoint & center, int rx, int ry )

This is an overloaded function.

Draws the ellipse positioned at center with radii rx and ry.

This function was introduced in Qt 4.4.

void QPainter::drawImage ( const QRectF & target, const QImage & image, const QRectF & sourceQt::ImageConversionFlags flags = Qt::AutoColor )

Draws the rectangular portion source of the given image into the target rectangle in the paint device.

Note: The image is scaled to fit the rectangle, if both the image and rectangle size disagree.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to specify how you would prefer this to happen.

 

 QRectF target(10.0, 20.0, 80.0, 60.0);
 QRectF source(0.0, 0.0, 70.0, 40.0);
 QImage image(":/images/myImage.png");

 QPainter painter(this);
 painter.drawImage(target, image, source);

 

void QPainter::drawImage ( const QRect & target, const QImage & image, const QRect & sourceQt::ImageConversionFlags flags = Qt::AutoColor )

This is an overloaded function.

Draws the rectangular portion source of the given image into the target rectangle in the paint device.

Note: The image is scaled to fit the rectangle, if both the image and rectangle size disagree.

void QPainter::drawImage ( const QPointF & point, const QImage & image )

This is an overloaded function.

Draws the given image at the given point.

void QPainter::drawImage ( const QPoint & point, const QImage & image )

This is an overloaded function.

Draws the given image at the given point.

void QPainter::drawImage ( const QPointF & point, const QImage & image, const QRectF & sourceQt::ImageConversionFlags flags = Qt::AutoColor )

This is an overloaded function.

Draws the rectangular portion source of the given image with its origin at the given point.

void QPainter::drawImage ( const QPoint & point, const QImage & image, const QRect & sourceQt::ImageConversionFlags flags = Qt::AutoColor )

This is an overloaded function.

Draws the rectangular portion source of the given image with its origin at the given point.

void QPainter::drawImage ( const QRectF & rectangle, const QImage & image )

This is an overloaded function.

Draws the given image into the given rectangle.

Note: The image is scaled to fit the rectangle, if both the image and rectangle size disagree.

void QPainter::drawImage ( const QRect & rectangle, const QImage & image )

This is an overloaded function.

Draws the given image into the given rectangle.

Note: The image is scaled to fit the rectangle, if both the image and rectangle size disagree.

void QPainter::drawImage ( int x, int y, const QImage & image, int sx = 0, int sy = 0, int sw = -1, int sh = -1, Qt::ImageConversionFlags flags = Qt::AutoColor )

This is an overloaded function.

Draws an image at (xy) by copying a part of image into the paint device.

(xy) specifies the top-left point in the paint device that is to be drawn onto. (sxsy) specifies the top-left point in image that is to be drawn. The default is (0, 0).

(swsh) specifies the size of the image that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the image.

void QPainter::drawLine ( const QLineF & line )

Draws a line defined by line.

 

 QLineF line(10.0, 80.0, 90.0, 20.0);

 QPainter(this);
 painter.drawLine(line);

 

void QPainter::drawLine ( const QLine & line )

This is an overloaded function.

Draws a line defined by line.

void QPainter::drawLine ( const QPoint & p1, const QPoint & p2 )

This is an overloaded function.

Draws a line from p1 to p2.

void QPainter::drawLine ( const QPointF & p1, const QPointF & p2 )

This is an overloaded function.

Draws a line from p1 to p2.

void QPainter::drawLine ( int x1, int y1, int x2, int y2 )

This is an overloaded function.

Draws a line from (x1y1) to (x2y2) and sets the current pen position to (x2y2).

void QPainter::drawLines ( const QLineF * lines, int lineCount )

Draws the first lineCount lines in the array lines using the current pen.

void QPainter::drawLines ( const QLine * lines, int lineCount )

This is an overloaded function.

Draws the first lineCount lines in the array lines using the current pen.

void QPainter::drawLines ( const QPointF * pointPairs, int lineCount )

This is an overloaded function.

Draws the first lineCount lines in the array pointPairs using the current pen. The lines are specified as pairs of points so the number of entries in pointPairs must be at least lineCount * 2.

void QPainter::drawLines ( const QPoint * pointPairs, int lineCount )

This is an overloaded function.

Draws the first lineCount lines in the array pointPairs using the current pen.

void QPainter::drawLines ( const QVector<QPointF> & pointPairs )

This is an overloaded function.

Draws a line for each pair of points in the vector pointPairs using the current pen. If there is an odd number of points in the array, the last point will be ignored.

void QPainter::drawLines ( const QVector<QPoint> & pointPairs )

This is an overloaded function.

Draws a line for each pair of points in the vector pointPairs using the current pen.

void QPainter::drawLines ( const QVector<QLineF> & lines )

This is an overloaded function.

Draws the set of lines defined by the list lines using the current pen and brush.

void QPainter::drawLines ( const QVector<QLine> & lines )

This is an overloaded function.

Draws the set of lines defined by the list lines using the current pen and brush.

void QPainter::drawPath ( const QPainterPath & path )

Draws the given painter path using the current pen for outline and the current brush for filling.

 

 QPainterPath path;
 path.moveTo(20, 80);
 path.lineTo(20, 30);
 path.cubicTo(80, 0, 50, 50, 80, 80);

 QPainter painter(this);
 painter.drawPath(path);

 

void QPainter::drawPicture ( const QPointF & point, const QPicture & picture )

Replays the given picture at the given point.

The QPicture class is a paint device that records and replays QPainter commands. A picture serializes the painter commands to an IO device in a platform-independent format. Everything that can be painted on a widget or pixmap can also be stored in a picture.

This function does exactly the same as QPicture::play() when called with point = QPoint(0, 0).

 

 QPicture picture;
 QPointF point(10.0, 20.0)
 picture.load("drawing.pic");

 QPainter painter(this);
 painter.drawPicture(0, 0, picture);

 

void QPainter::drawPicture ( const QPoint & point, const QPicture & picture )

This is an overloaded function.

Replays the given picture at the given point.

void QPainter::drawPicture ( int x, int y, const QPicture & picture )

This is an overloaded function.

Draws the given picture at point (xy).

void QPainter::drawPie ( const QRectF & rectangle, int startAngle, int spanAngle )

Draws a pie defined by the given rectanglestartAngle and and spanAngle.

The pie is filled with the current brush().

The startAngle and spanAngle must be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);
 int startAngle = 30 * 16;
 int spanAngle = 120 * 16;

 QPainter painter(this);
 painter.drawPie(rectangle, startAngle, spanAngle);

 

void QPainter::drawPie ( const QRect & rectangle, int startAngle, int spanAngle )

This is an overloaded function.

Draws a pie defined by the given rectanglestartAngle and and spanAngle.

void QPainter::drawPie ( int x, int y, int width, int height, int startAngle, int spanAngle )

This is an overloaded function.

Draws the pie defined by the rectangle beginning at (xy) with the specified width and height, and the given startAngle and spanAngle.

void QPainter::drawPixmap ( const QRectF & target, const QPixmap & pixmap, const QRectF & source )

Draws the rectangular portion source of the given pixmap into the given target in the paint device.

Note: The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.

 

 QRectF target(10.0, 20.0, 80.0, 60.0);
 QRectF source(0.0, 0.0, 70.0, 40.0);
 QPixmap pixmap(":myPixmap.png");

 QPainter(this);
 painter.drawPixmap(target, image, source);

 

If pixmap is a QBitmap it is drawn with the bits that are “set” using the pens color. If backgroundMode is Qt::OpaqueMode, the “unset” bits are drawn using the color of the background brush; if backgroundMode isQt::TransparentMode, the “unset” bits are transparent. Drawing bitmaps with gradient or texture colors is not supported.

void QPainter::drawPixmap ( const QRect & target, const QPixmap & pixmap, const QRect & source )

This is an overloaded function.

Draws the rectangular portion source of the given pixmap into the given target in the paint device.

Note: The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.

void QPainter::drawPixmap ( const QPointF & point, const QPixmap & pixmap, const QRectF & source )

This is an overloaded function.

Draws the rectangular portion source of the given pixmap with its origin at the given point.

void QPainter::drawPixmap ( const QPoint & point, const QPixmap & pixmap, const QRect & source )

This is an overloaded function.

Draws the rectangular portion source of the given pixmap with its origin at the given point.

void QPainter::drawPixmap ( const QPointF & point, const QPixmap & pixmap )

This is an overloaded function.

Draws the given pixmap with its origin at the given point.

void QPainter::drawPixmap ( const QPoint & point, const QPixmap & pixmap )

This is an overloaded function.

Draws the given pixmap with its origin at the given point.

void QPainter::drawPixmap ( int x, int y, const QPixmap & pixmap )

This is an overloaded function.

Draws the given pixmap at position (xy).

void QPainter::drawPixmap ( const QRect & rectangle, const QPixmap & pixmap )

This is an overloaded function.

Draws the given pixmap into the given rectangle.

Note: The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.

void QPainter::drawPixmap ( int x, int y, int width, int height, const QPixmap & pixmap )

This is an overloaded function.

Draws the pixmap into the rectangle at position (xy) with the given width and height.

void QPainter::drawPixmap ( int x, int y, int w, int h, const QPixmap & pixmap, int sx, int sy, int sw, int sh )

This is an overloaded function.

Draws the rectangular portion with the origin (sxsy), width sw and height sh, of the given pixmap , at the point (xy), with a width of w and a height of h. If sw or sh are equal to zero the width/height of the pixmap is used and adjusted by the offset sx/sy;

void QPainter::drawPixmap ( int x, int y, const QPixmap & pixmap, int sx, int sy, int sw, int sh )

This is an overloaded function.

Draws a pixmap at (xy) by copying a part of the given pixmap into the paint device.

(xy) specifies the top-left point in the paint device that is to be drawn onto. (sxsy) specifies the top-left point in pixmap that is to be drawn. The default is (0, 0).

(swsh) specifies the size of the pixmap that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the pixmap.

void QPainter::drawPoint ( const QPointF & position )

Draws a single point at the given position using the current pen’s color.

void QPainter::drawPoint ( const QPoint & position )

This is an overloaded function.

Draws a single point at the given position using the current pen’s color.

void QPainter::drawPoint ( int x, int y )

This is an overloaded function.

Draws a single point at position (xy).

void QPainter::drawPoints ( const QPointF * points, int pointCount )

Draws the first pointCount points in the array points using the current pen’s color.

void QPainter::drawPoints ( const QPoint * points, int pointCount )

This is an overloaded function.

Draws the first pointCount points in the array points using the current pen’s color.

void QPainter::drawPoints ( const QPolygonF & points )

This is an overloaded function.

Draws the points in the vector points.

void QPainter::drawPoints ( const QPolygon & points )

This is an overloaded function.

Draws the points in the vector points.

void QPainter::drawPolygon ( const QPointF * points, int pointCountQt::FillRule fillRule = Qt::OddEvenFill )

Draws the polygon defined by the first pointCount points in the array points using the current pen and brush.

 

 static const QPointF points[4] = {
     QPointF(10.0, 80.0),
     QPointF(20.0, 10.0),
     QPointF(80.0, 30.0),
     QPointF(90.0, 70.0)
 };

 QPainter painter(this);
 painter.drawPolygon(points, 4);

 

The first point is implicitly connected to the last point, and the polygon is filled with the current brush().

If fillRule is Qt::WindingFill, the polygon is filled using the winding fill algorithm. If fillRule is Qt::OddEvenFill, the polygon is filled using the odd-even fill algorithm. See Qt::FillRule for a more detailed description of these fill rules.

void QPainter::drawPolygon ( const QPoint * points, int pointCountQt::FillRule fillRule = Qt::OddEvenFill )

This is an overloaded function.

Draws the polygon defined by the first pointCount points in the array points.

void QPainter::drawPolygon ( const QPolygonF & pointsQt::FillRule fillRule = Qt::OddEvenFill )

This is an overloaded function.

Draws the polygon defined by the given points using the fill rule fillRule.

void QPainter::drawPolygon ( const QPolygon & pointsQt::FillRule fillRule = Qt::OddEvenFill )

This is an overloaded function.

Draws the polygon defined by the given points using the fill rule fillRule.

void QPainter::drawPolyline ( const QPointF * points, int pointCount )

Draws the polyline defined by the first pointCount points in points using the current pen.

Note that unlike the drawPolygon() function the last point is not connected to the first, neither is the polyline filled.

 

 static const QPointF points[3] = {
     QPointF(10.0, 80.0),
     QPointF(20.0, 10.0),
     QPointF(80.0, 30.0),
 };

 QPainter painter(this);
 painter.drawPolyline(points, 3);

 

void QPainter::drawPolyline ( const QPoint * points, int pointCount )

This is an overloaded function.

Draws the polyline defined by the first pointCount points in points using the current pen.

void QPainter::drawPolyline ( const QPolygonF & points )

This is an overloaded function.

Draws the polyline defined by the given points using the current pen.

void QPainter::drawPolyline ( const QPolygon & points )

This is an overloaded function.

Draws the polyline defined by the given points using the current pen.

void QPainter::drawRect ( const QRectF & rectangle )

Draws the current rectangle with the current pen and brush.

A filled rectangle has a size of rectangle.size(). A stroked rectangle has a size of rectangle.size() plus the pen width.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);

 QPainter painter(this);
 painter.drawRect(rectangle);

 

void QPainter::drawRect ( const QRect & rectangle )

This is an overloaded function.

Draws the current rectangle with the current pen and brush.

void QPainter::drawRect ( int x, int y, int width, int height )

This is an overloaded function.

Draws a rectangle with upper left corner at (xy) and with the given width and height.

void QPainter::drawRects ( const QRectF * rectangles, int rectCount )

Draws the first rectCount of the given rectangles using the current pen and brush.

void QPainter::drawRects ( const QRect * rectangles, int rectCount )

This is an overloaded function.

Draws the first rectCount of the given rectangles using the current pen and brush.

void QPainter::drawRects ( const QVector<QRectF> & rectangles )

This is an overloaded function.

Draws the given rectangles using the current pen and brush.

void QPainter::drawRects ( const QVector<QRect> & rectangles )

This is an overloaded function.

Draws the given rectangles using the current pen and brush.

void QPainter::drawRoundedRect ( const QRectF & rectqreal xRadiusqreal yRadiusQt::SizeMode mode = Qt::AbsoluteSize )

Draws the given rectangle rect with rounded corners.

The xRadius and yRadius arguments specify the radii of the ellipses defining the corners of the rounded rectangle. When mode is Qt::RelativeSizexRadius and yRadius are specified in percentage of half the rectangle’s width and height respectively, and should be in the range 0.0 to 100.0.

A filled rectangle has a size of rect.size(). A stroked rectangle has a size of rect.size() plus the pen width.

 

 QRectF rectangle(10.0, 20.0, 80.0, 60.0);

 QPainter painter(this);
 painter.drawRoundedRect(rectangle, 20.0, 15.0);

 

void QPainter::drawRoundedRect ( const QRect & rectqreal xRadiusqreal yRadiusQt::SizeMode mode = Qt::AbsoluteSize )

This is an overloaded function.

Draws the given rectangle rect with rounded corners.

void QPainter::drawRoundedRect ( int x, int y, int w, int hqreal xRadiusqreal yRadiusQt::SizeMode mode = Qt::AbsoluteSize )

This is an overloaded function.

Draws the given rectangle xywh with rounded corners.

void QPainter::drawText ( const QPointF & position, const QString & text )

Draws the given text with the currently defined text direction, beginning at the given position.

This function does not handle the newline character (\n), as it cannot break text into multiple lines, and it cannot display the newline character. Use the QPainter::drawText() overload that takes a rectangle instead if you want to draw multiple lines of text with the newline character, or if you want the text to be wrapped.

By default, QPainter draws text anti-aliased.

Note: The y-position is used as the baseline of the font.

void QPainter::drawText ( const QPoint & position, const QString & text )

This is an overloaded function.

Draws the given text with the currently defined text direction, beginning at the given position.

By default, QPainter draws text anti-aliased.

Note: The y-position is used as the baseline of the font.

void QPainter::drawText ( const QRectF & rectangle, int flags, const QString & textQRectF * boundingRect = 0 )

This is an overloaded function.

Draws the given text within the provided rectangle.

 

 QPainter painter(this);
 painter.drawText(rect, Qt::AlignCenter, tr("Qt by\nNokia"));

 

The boundingRect (if not null) is set to the what the bounding rectangle should be in order to enclose the whole text. The flags argument is a bitwise OR of the following flags:

By default, QPainter draws text anti-aliased.

Note: The y-coordinate of rectangle is used as the top of the font..

void QPainter::drawText ( const QRect & rectangle, int flags, const QString & textQRect * boundingRect = 0 )

This is an overloaded function.

Draws the given text within the provided rectangle according to the specified flags. The boundingRect (if not null) is set to the what the bounding rectangle should be in order to enclose the whole text.

By default, QPainter draws text anti-aliased.

Note: The y-coordinate of rectangle is used as the top of the font.

void QPainter::drawText ( int x, int y, const QString & text )

This is an overloaded function.

Draws the given text at position (xy), using the painter’s currently defined text direction.

By default, QPainter draws text anti-aliased.

Note: The y-position is used as the baseline of the font.

void QPainter::drawText ( int x, int y, int width, int height, int flags, const QString & textQRect * boundingRect = 0 )

This is an overloaded function.

Draws the given text within the rectangle with origin (xy), width and height.

The boundingRect (if not null) is set to the actual bounding rectangle of the output. The flags argument is a bitwise OR of the following flags:

By default, QPainter draws text anti-aliased.

Note: The y-position is used as the baseline of the font.

void QPainter::drawText ( const QRectF & rectangle, const QString & text, const QTextOption & option = QTextOption() )

This is an overloaded function.

Draws the given text in the rectangle specified using the option to control its positioning and orientation.

By default, QPainter draws text anti-aliased.

Note: The y-coordinate of rectangle is used as the top of the font.

void QPainter::drawTiledPixmap ( const QRectF & rectangle, const QPixmap & pixmap, const QPointF & position = QPointF() )

Draws a tiled pixmap, inside the given rectangle with its origin at the given position.

Calling drawTiledPixmap() is similar to calling drawPixmap() several times to fill (tile) an area with a pixmap, but is potentially much more efficient depending on the underlying window system.

void QPainter::drawTiledPixmap ( const QRect & rectangle, const QPixmap & pixmap, const QPoint & position = QPoint() )

This is an overloaded function.

Draws a tiled pixmap, inside the given rectangle with its origin at the given position.

void QPainter::drawTiledPixmap ( int x, int y, int width, int height, const QPixmap & pixmap, int sx = 0, int sy = 0 )

This is an overloaded function.

Draws a tiled pixmap in the specified rectangle.

(xy) specifies the top-left point in the paint device that is to be drawn onto; with the given width and height. (sxsy) specifies the top-left point in the pixmap that is to be drawn; this defaults to (0, 0).

bool QPainter::end ()

Ends painting. Any resources used while painting are released. You don’t normally need to call this since it is called by the destructor.

Returns true if the painter is no longer active; otherwise returns false.

void QPainter::eraseRect ( const QRectF & rectangle )

Erases the area inside the given rectangle. Equivalent to calling

 fillRect(rectangle, background()).

void QPainter::eraseRect ( const QRect & rectangle )

This is an overloaded function.

Erases the area inside the given rectangle.

void QPainter::eraseRect ( int x, int y, int width, int height )

This is an overloaded function.

Erases the area inside the rectangle beginning at (xy) with the given width and height.

void QPainter::fillPath ( const QPainterPath & path, const QBrush & brush )

Fills the given path using the given brush. The outline is not drawn.

Alternatively, you can specify a QColor instead of a QBrush; the QBrush constructor (taking a QColor argument) will automatically create a solid pattern brush.

void QPainter::fillRect ( const QRectF & rectangle, const QBrush & brush )

Fills the given rectangle with the brush specified.

Alternatively, you can specify a QColor instead of a QBrush; the QBrush constructor (taking a QColor argument) will automatically create a solid pattern brush.

void QPainter::fillRect ( int x, int y, int width, int heightQt::BrushStyle style )

This is an overloaded function.

Fills the rectangle beginning at (xy) with the given width and height, using the brush style specified.

void QPainter::fillRect ( const QRect & rectangleQt::BrushStyle style )

This is an overloaded function.

Fills the given rectangle with the brush style specified.

void QPainter::fillRect ( const QRectF & rectangleQt::BrushStyle style )

This is an overloaded function.

Fills the given rectangle with the brush style specified.

void QPainter::fillRect ( const QRect & rectangle, const QBrush & brush )

This is an overloaded function.

Fills the given rectangle with the specified brush.

void QPainter::fillRect ( const QRect & rectangle, const QColor & color )

This is an overloaded function.

Fills the given rectangle with the color specified.

void QPainter::fillRect ( const QRectF & rectangle, const QColor & color )

This is an overloaded function.

Fills the given rectangle with the color specified.

void QPainter::fillRect ( int x, int y, int width, int height, const QBrush & brush )

This is an overloaded function.

Fills the rectangle beginning at (xy) with the given width and height, using the given brush.

void QPainter::fillRect ( int x, int y, int width, int height, const QColor & color )

This is an overloaded function.

Fills the rectangle beginning at (xy) with the given width and height, using the given color.

void QPainter::fillRect ( int x, int y, int width, int heightQt::GlobalColor color )

This is an overloaded function.

Fills the rectangle beginning at (xy) with the given width and height, using the given color.

void QPainter::fillRect ( const QRect & rectangleQt::GlobalColor color )

This is an overloaded function.

Fills the given rectangle with the specified color.

void QPainter::fillRect ( const QRectF & rectangleQt::GlobalColor color )

This is an overloaded function.

Fills the given rectangle with the specified color.

const QFont & QPainter::font () const

Returns the currently set font used for drawing text.

QFontInfo QPainter::fontInfo () const

Returns the font info for the painter if the painter is active. Otherwise, the return value is undefined.

QFontMetrics QPainter::fontMetrics () const

Returns the font metrics for the painter if the painter is active. Otherwise, the return value is undefined.

bool QPainter::hasClipping () const

Returns true if clipping has been set; otherwise returns false.

void QPainter::initFrom ( const QWidget * widget )

Initializes the painters pen, background and font to the same as the given widget. This function is called automatically when the painter is opened on a QWidget.

bool QPainter::isActive () const

Returns true if begin() has been called and end() has not yet been called; otherwise returns false.

Qt::LayoutDirection QPainter::layoutDirection () const

Returns the layout direction used by the painter when drawing text.

qreal QPainter::opacity () const

Returns the opacity of the painter. The default value is 1.

QPaintEngine * QPainter::paintEngine () const

Returns the paint engine that the painter is currently operating on if the painter is active; otherwise 0.

const QPen & QPainter::pen () const

Returns the painter’s current pen.

QPaintDevice * QPainter::redirected ( const QPaintDevice * deviceQPoint * offset = 0 )   [static]

Returns the replacement for given device. The optional out parameter offset returns the offset within the replaced device.

Note: This function is thread-safe.

RenderHints QPainter::renderHints () const

Returns a flag that specifies the rendering hints that are set for this painter.

void QPainter::resetMatrix ()

Resets any transformations that were made using translate(), scale(), shear(), rotate(), setWorldMatrix(), setViewport() and setWindow().

It is advisable to use resetTransform() instead of this function to preserve the properties of perspective transformations.

void QPainter::resetTransform ()

Resets any transformations that were made using translate(), scale(), shear(), rotate(), setWorldTransform(), setViewport() and setWindow().

void QPainter::restore ()

Restores the current painter state (pops a saved state off the stack).

void QPainter::restoreRedirected ( const QPaintDevice * device )   [static]

Restores the previous redirection for the given device after a call to setRedirected().

Note: This function is thread-safe.

void QPainter::rotate ( qreal angle )

Rotates the coordinate system the given angle clockwise.

void QPainter::save ()

Saves the current painter state (pushes the state onto a stack). A save() must be followed by a corresponding restore(); the end() function unwinds the stack.

void QPainter::scale ( qreal sxqreal sy )

Scales the coordinate system by (sxsy).

void QPainter::setBackground ( const QBrush & brush )

Sets the background brush of the painter to the given brush.

The background brush is the brush that is filled in when drawing opaque text, stippled lines and bitmaps. The background brush has no effect in transparent background mode (which is the default).

void QPainter::setBackgroundMode ( Qt::BGMode mode )

Sets the background mode of the painter to the given mode

Qt::TransparentMode (the default) draws stippled lines and text without setting the background pixels. Qt::OpaqueMode fills these space with the current background color.

Note that in order to draw a bitmap or pixmap transparently, you must use QPixmap::setMask().

void QPainter::setBrush ( const QBrush & brush )

Sets the painter’s brush to the given brush.

The painter’s brush defines how shapes are filled.

void QPainter::setBrush ( Qt::BrushStyle style )

This is an overloaded function.

Sets the painter’s brush to black color and the specified style.

void QPainter::setBrushOrigin ( const QPointF & position )

Sets the brush origin to position.

The brush origin specifies the (0, 0) coordinate of the painter’s brush. This setting only applies to pattern brushes and pixmap brushes.

Note that while the brushOrigin() was necessary to adopt the parent’s background for a widget in Qt 3, this is no longer the case since the Qt 4 painter doesn’t paint the background unless you explicitly tell it to do so by setting the widget’sautoFillBackground property to true.

void QPainter::setBrushOrigin ( const QPoint & position )

This is an overloaded function.

Sets the brush’s origin to the given position.

void QPainter::setBrushOrigin ( int x, int y )

This is an overloaded function.

Sets the brush’s origin to point (xy).

void QPainter::setClipPath ( const QPainterPath & pathQt::ClipOperation operation = Qt::ReplaceClip )

Enables clipping, and sets the clip path for the painter to the given path, with the clip operation.

Note that the clip path is specified in logical (painter) coordinates.

void QPainter::setClipRect ( const QRectF & rectangleQt::ClipOperation operation = Qt::ReplaceClip )

Enables clipping, and sets the clip region to the given rectangle using the given clip operation. The default operation is to replace the current clip rectangle.

Note that the clip rectangle is specified in logical (painter) coordinates.

void QPainter::setClipRect ( int x, int y, int width, int heightQt::ClipOperation operation = Qt::ReplaceClip )

Enables clipping, and sets the clip region to the rectangle beginning at (xy) with the given width and height.

void QPainter::setClipRect ( const QRect & rectangleQt::ClipOperation operation = Qt::ReplaceClip )

This is an overloaded function.

Enables clipping, and sets the clip region to the given rectangle using the given clip operation.

void QPainter::setClipRegion ( const QRegion & regionQt::ClipOperation operation = Qt::ReplaceClip )

Sets the clip region to the given region using the specified clip operation. The default clip operation is to replace the current clip region.

Note that the clip region is given in logical coordinates.

void QPainter::setClipping ( bool enable )

Enables clipping if enable is true, or disables clipping if enable is false.

void QPainter::setCompositionMode ( CompositionMode mode )

Sets the composition mode to the given mode.

Warning: You can only set the composition mode for QPainter objects that operates on a QImage.

void QPainter::setFont ( const QFont & font )

Sets the painter’s font to the given font.

This font is used by subsequent drawText() functions. The text color is the same as the pen color.

If you set a font that isn’t available, Qt finds a close match. font() will return what you set using setFont() and fontInfo() returns the font actually being used (which may be the same).

void QPainter::setLayoutDirection ( Qt::LayoutDirection direction )

Sets the layout direction used by the painter when drawing text, to the specified direction.

void QPainter::setOpacity ( qreal opacity )

Sets the opacity of the painter to opacity. The value should be in the range 0.0 to 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.

Opacity set on the painter will apply to all drawing operations individually.

void QPainter::setPen ( const QPen & pen )

Sets the painter’s pen to be the given pen.

The pen defines how to draw lines and outlines, and it also defines the text color.

void QPainter::setPen ( const QColor & color )

This is an overloaded function.

Sets the painter’s pen to have style Qt::SolidLine, width 0 and the specified color.

void QPainter::setPen ( Qt::PenStyle style )

This is an overloaded function.

Sets the painter’s pen to have the given style, width 0 and black color.

void QPainter::setRedirected ( const QPaintDevice * deviceQPaintDevice * replacement, const QPoint & offset = QPoint() )   [static]

Redirects all paint commands for the given paint device, to the replacement device. The optional point offset defines an offset within the source device.

The redirection will not be effective until the begin() function has been called; make sure to call end() for the given device‘s painter (if any) before redirecting. Call restoreRedirected() to restore the previous redirection.

In general, you’ll probably find that calling QPixmap::grabWidget() or QPixmap::grabWindow() is an easier solution.

Note: This function is thread-safe.

void QPainter::setRenderHint ( RenderHint hint, bool on = true )

Sets the given render hint on the painter if on is true; otherwise clears the render hint.

void QPainter::setRenderHints ( RenderHints hints, bool on = true )

Sets the given render hints on the painter if on is true; otherwise clears the render hints.

void QPainter::setTransform ( const QTransform & transform, bool combine = false )

Sets the world transformation matrix. If combine is true, the specified transform is combined with the current matrix; otherwise it replaces the current matrix.

This function has been added for compatibility with setMatrix(), but as with setMatrix() the preferred method of setting a transformation on the painter is through setWorldTransform().

This function was introduced in Qt 4.3.

void QPainter::setViewTransformEnabled ( bool enable )

Enables view transformations if enable is true, or disables view transformations if enable is false.

void QPainter::setViewport ( const QRect & rectangle )

Sets the painter’s viewport rectangle to the given rectangle, and enables view transformations.

The viewport rectangle is part of the view transformation. The viewport specifies the device coordinate system. Its sister, the window(), specifies the logical coordinate system.

The default viewport rectangle is the same as the device’s rectangle.

void QPainter::setViewport ( int x, int y, int width, int height )

This is an overloaded function.

Sets the painter’s viewport rectangle to be the rectangle beginning at (xy) with the given width and height.

void QPainter::setWindow ( const QRect & rectangle )

Sets the painter’s window to the given rectangle, and enables view transformations.

The window rectangle is part of the view transformation. The window specifies the logical coordinate system. Its sister, the viewport(), specifies the device coordinate system.

The default window rectangle is the same as the device’s rectangle.

void QPainter::setWindow ( int x, int y, int width, int height )

This is an overloaded function.

Sets the painter’s window to the rectangle beginning at (xy) and the given width and height.

void QPainter::setWorldMatrix ( const QMatrix & matrix, bool combine = false )

Sets the transformation matrix to matrix and enables transformations.

Note: It is advisable to use setWorldTransform() instead of this function to preserve the properties of perspective transformations.

If combine is true, then matrix is combined with the current transformation matrix; otherwise matrix replaces the current transformation matrix.

If matrix is the identity matrix and combine is false, this function calls setWorldMatrixEnabled(false). (The identity matrix is the matrix where QMatrix::m11() and QMatrix::m22() are 1.0 and the rest are 0.0.)

The following functions can transform the coordinate system without using a QMatrix:

They operate on the painter’s worldMatrix() and are implemented like this:

 void QPainter::rotate(qreal angle)
 {
     QMatrix matrix;
     matrix.rotate(angle);
     setWorldMatrix(matrix, true);
 }

Note that when using setWorldMatrix() function you should always have combine be true when you are drawing into a QPicture. Otherwise it may not be possible to replay the picture with additional transformations; using the translate(),scale(), etc. convenience functions is safe.

For more information about the coordinate system, transformations and window-viewport conversion, see The Coordinate System documentation.

void QPainter::setWorldMatrixEnabled ( bool enable )

Enables transformations if enable is true, or disables transformations if enable is false. The world transformation matrix is not changed.

void QPainter::setWorldTransform ( const QTransform & matrix, bool combine = false )

Sets the world transformation matrix. If combine is true, the specified matrix is combined with the current matrix; otherwise it replaces the current matrix.

void QPainter::shear ( qreal shqreal sv )

Shears the coordinate system by (shsv).

void QPainter::strokePath ( const QPainterPath & path, const QPen & pen )

Draws the outline (strokes) the path path with the pen specified by pen

bool QPainter::testRenderHint ( RenderHint hint ) const

Returns true if hint is set; otherwise returns false.

const QTransform & QPainter::transform () const

Returns the world transformation matrix.

void QPainter::translate ( const QPointF & offset )

Translates the coordinate system by the given offset; i.e. the given offset is added to points.

void QPainter::translate ( const QPoint & offset )

This is an overloaded function.

Translates the coordinate system by the given offset.

void QPainter::translate ( qreal dxqreal dy )

This is an overloaded function.

Translates the coordinate system by the vector (dxdy).

bool QPainter::viewTransformEnabled () const

Returns true if view transformation is enabled; otherwise returns false.

QRect QPainter::viewport () const

Returns the viewport rectangle.

QRect QPainter::window () const

Returns the window rectangle.

const QMatrix & QPainter::worldMatrix () const

Returns the world transformation matrix.

It is advisable to use worldTransform() because worldMatrix() does not preserve the properties of perspective transformations.

bool QPainter::worldMatrixEnabled () const

Returns true if world transformation is enabled; otherwise returns false.

const QTransform & QPainter::worldTransform () const

Returns the world transformation matrix.


Não membros relacionados

void qDrawPlainRect ( QPainter * painter, int x, int y, int width, int height, const QColor & lineColor, int lineWidth = 1, const QBrush * fill = 0 )

Draws the plain rectangle beginning at (xy) with the given width and height, using the specified painterlineColor and lineWidth. The rectangle’s interior is filled with the fill brush unless fill is 0.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a plain rectangle:

 QFrame frame:
 frame.setFrameStyle(QFrame::Box | QFrame::Plain);

void qDrawPlainRect ( QPainter * painter, const QRect & rect, const QColor & lineColor, int lineWidth = 1, const QBrush * fill = 0 )

This is an overloaded function.

Draws the plain rectangle specified by rect using the given painterlineColor and lineWidth. The rectangle’s interior is filled with the fill brush unless fill is 0.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a plain rectangle:

 QFrame frame:
 frame.setFrameStyle(QFrame::Box | QFrame::Plain);

void qDrawShadeLine ( QPainter * painter, int x1, int y1, int x2, int y2, const QPalette & palette, bool sunken = true, int lineWidth = 1, int midLineWidth = 0 )

Draws a horizontal (y1 == y2) or vertical (x1 == x2) shaded line using the given painter. Note that nothing is drawn if y1 != y2 and x1 != x2 (i.e. the line is neither horizontal nor vertical).

The provided palette specifies the shading colors (lightdark and middle colors). The given lineWidth specifies the line width for each of the lines; it is not the total line width. The given midLineWidth specifies the width of a middle line drawn in the QPalette::mid() color.

The line appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded line:

 QFrame frame:
 frame.setFrameStyle(QFrame::HLine | QFrame::Sunken);

void qDrawShadeLine ( QPainter * painter, const QPoint & p1, const QPoint & p2, const QPalette & palette, bool sunken = true, int lineWidth = 1, int midLineWidth = 0 )

This is an overloaded function.

Draws a horizontal or vertical shaded line between p1 and p2 using the given painter. Note that nothing is drawn if the line between the points would be neither horizontal nor vertical.

The provided palette specifies the shading colors (lightdark and middle colors). The given lineWidth specifies the line width for each of the lines; it is not the total line width. The given midLineWidth specifies the width of a middle line drawn in the QPalette::mid() color.

The line appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded line:

 QFrame frame:
 frame.setFrameStyle(QFrame::HLine | QFrame::Sunken);

void qDrawShadePanel ( QPainter * painter, int x, int y, int width, int height, const QPalette & palette, bool sunken = false, int lineWidth = 1, const QBrush * fill = 0 )

Draws the shaded panel beginning at (xy) with the given width and height using the provided painter and the given lineWidth.

The given palette specifies the shading colors (lightdark and middle colors). The panel’s interior is filled with the fill brush unless fill is 0.

The panel appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded panel:

 QFrame frame:
 frame.setFrameStyle( QFrame::Panel | QFrame::Sunken);

void qDrawShadePanel ( QPainter * painter, const QRect & rect, const QPalette & palette, bool sunken = false, int lineWidth = 1, const QBrush * fill = 0 )

This is an overloaded function.

Draws the shaded panel at the rectangle specified by rect using the given painter and the given lineWidth.

The given palette specifies the shading colors (lightdark and middle colors). The panel’s interior is filled with the fill brush unless fill is 0.

The panel appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded panel:

 QFrame frame:
 frame.setFrameStyle( QFrame::Panel | QFrame::Sunken);

void qDrawShadeRect ( QPainter * painter, int x, int y, int width, int height, const QPalette & palette, bool sunken = false, int lineWidth = 1, int midLineWidth = 0, constQBrush * fill = 0 )

Draws the shaded rectangle beginning at (xy) with the given width and height using the provided painter.

The provide palette specifies the shading colors (lightdark and middle colors. The given lineWidth specifies the line width for each of the lines; it is not the total line width. The midLineWidth specifies the width of a middle line drawn in the QPalette::mid() color. The rectangle’s interior is filled with the fill brush unless fill is 0.

The rectangle appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded rectangle:

 QFrame frame:
 frame.setFrameStyle(QFrame::Box | QFrame::Raised);

void qDrawShadeRect ( QPainter * painter, const QRect & rect, const QPalette & palette, bool sunken = false, int lineWidth = 1, int midLineWidth = 0, const QBrush * fill = 0 )

This is an overloaded function.

Draws the shaded rectangle specified by rect using the given painter.

The provide palette specifies the shading colors (lightdark and middle colors. The given lineWidth specifies the line width for each of the lines; it is not the total line width. The midLineWidth specifies the width of a middle line drawn in the QPalette::mid() color. The rectangle’s interior is filled with the fill brush unless fill is 0.

The rectangle appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded rectangle:

 QFrame frame:
 frame.setFrameStyle(QFrame::Box | QFrame::Raised);

void qDrawWinButton ( QPainter * painter, int x, int y, int width, int height, const QPalette & palette, bool sunken = false, const QBrush * fill = 0 )

Draws the Windows-style button specified by the given point (xy}, width and height using the provided painter with a line width of 2 pixels. The button’s interior is filled with the fill brush unless fill is 0.

The given palette specifies the shading colors (lightdark and middle colors).

The button appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style()-> Use the drawing functions in QStyle to make widgets that follow the current GUI style.

void qDrawWinButton ( QPainter * painter, const QRect & rect, const QPalette & palette, bool sunken = false, const QBrush * fill = 0 )

This is an overloaded function.

Draws the Windows-style button at the rectangle specified by rect using the given painter with a line width of 2 pixels. The button’s interior is filled with the fill brush unless fill is 0.

The given palette specifies the shading colors (lightdark and middle colors).

The button appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style()-> Use the drawing functions in QStyle to make widgets that follow the current GUI style.

void qDrawWinPanel ( QPainter * painter, int x, int y, int width, int height, const QPalette & palette, bool sunken = false, const QBrush * fill = 0 )

Draws the Windows-style panel specified by the given point(xy), width and height using the provided painter with a line width of 2 pixels. The button’s interior is filled with the fill brush unless fill is 0.

The given palette specifies the shading colors. The panel appears sunken if sunken is true, otherwise raised.

Warning: This function does not look at QWidget::style() or QApplication::style(). Use the drawing functions in QStyle to make widgets that follow the current GUI style.

Alternatively you can use a QFrame widget and apply the QFrame::setFrameStyle() function to display a shaded panel:

 QFrame frame:
 frame.setFrameStyle(QFrame::WinPanel | QFrame::Raised);

Traduzido de http://doc.trolltech.com/4.5/qpainter.html