Qt Painter

QPainter provides highly optimized functions to do most of the drawing GUI programs require. It can draw everything from simple lines to complex shapes like pies and chords. It can also draw aligned text and pixmaps. Normally, it draws in a “natural” coordinate system, but it can also do view and world transformation. QPainter can operate on any object that inherits the QPaintDevice class.

The common use of QPainter is inside a widget’s paint event: Construct and customize (e.g. set the pen or the brush) the painter. Then draw. Remember to destroy the QPainter object after drawing. For example:

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

The core functionality of QPainter is drawing, but the class also provide several functions that allows you to customize QPainter’s settings and its rendering quality, and others that enable clipping. In addition you can control how different shapes are merged together by specifying the painter’s composition mode.

The isActive() function indicates whether the painter is active. A painter is activated by the begin() function and the constructor that takes a QPaintDevice argument. The end() function, and the destructor, deactivates it.

Together with the QPaintDevice and QPaintEngine classes, QPainter form the basis for Qt’s paint system. QPainter is the class used to perform drawing operations. QPaintDevice represents a device that can be painted on using a QPainter. QPaintEngine provides the interface that the painter uses to draw onto different types of devices. If the painter is active, device() returns the paint device on which the painter paints, and paintEngine() returns the paint engine that the painter is currently operating on. For more information, see the Paint System.

Settings

There are several settings that you can customize to make QPainter draw according to your preferences:

Note that some of these settings mirror settings in some paint devices, e.g. QWidget::font(). The QPainter::begin() function (or equivalently the QPainter constructor) copies these attributes from the paint device.

You can at any time save the QPainter’s state by calling the save() function which saves all the available settings on an internal stack. The restore() function pops them back.

void paintEvent(QPaintEvent *pe) override{
   QPainter painter(this);
   QColor color(200,0,0);
   QBrush brush(color,Qt::BrushStyle::FDiagPattern);
   QPen pen(QBrush(color),20,Qt::PenStyle::SolidLine,Qt::PenCapStyle::RoundCap,Qt::PenJoinStyle::RoundJoin);
   painter.setBrush(brush);
   painter.setPen(pen);
   QTransform translate,rotate;
   translate.translate(250,250);
   rotate.rotate(45);
   painter.setTransform(translate);
   painter.setTransform(rotate,true);//rotate*translate*point;
   painter.save();
   painter.drawRect(QRect(-150,-150,300,300));
   painter.drawLine(QLine(-200,200,200,200));
   painter.end();
}
//brush origin
void paintEvent(QPaintEvent *pe) override{
   QPainter painter(this);
   QColor color(200,0,0);
   QBrush brush(color,QPixmap("C:/Users/moham/OneDrive/Pictures/Capture.PNG"));
   QPen pen(QBrush(color),10,Qt::PenStyle::SolidLine,Qt::PenCapStyle::RoundCap,Qt::PenJoinStyle::RoundJoin);
   painter.setBrush(brush);
   painter.setBrushOrigin(100,100);//=brush.setTransform(QTransform::fromTranslate(100,100));
   painter.setPen(pen);
   painter.drawRect(QRect(100,100,300,300));
}

Drawing

QPainter provides functions to draw most primitives: drawPoint(), drawPoints(), drawLine(), drawRect(), drawRoundedRect(), drawEllipse(), drawArc(), drawPie(), drawChord(), drawPolyline(), drawPolygon(), drawConvexPolygon() and drawCubicBezier(). The two convenience functions, drawRects() and drawLines(), draw the given number of rectangles or lines in the given array of QRects or QLines using the current pen and brush.
The QPainter class also provides the fillRect() function which fills the given QRect, with the given QBrush, and the eraseRect() function that erases the area inside the given rectangle.
All of these functions have both integer and floating point versions.
If you need to draw a complex shape, especially if you need to do so repeatedly, consider creating a QPainterPath and drawing it using drawPath().
QPainter also provides the fillPath() function which fills the given QPainterPath with the given QBrush, and the strokePath() function that draws the outline of the given path (i.e. strokes the path).
you can use boundingRect() to get the width and height of text before draw text

Drawing Pixmaps and Images

There are functions to draw pixmaps/images, namely drawPixmap(), drawImage() and drawTiledPixmap(). Both drawPixmap() and drawImage() produce the same result, except that drawPixmap() is faster on-screen while drawImage() may be faster on a QPrinter or other devices.
There is a drawPicture() function that draws the contents of an entire QPicture. The drawPicture() function is the only function that disregards all the painter’s settings as QPicture has its own settings.

Rendering Quality

To get the optimal rendering result using QPainter, you should use the platform independent QImage as paint device; i.e. using QImage will ensure that the result has an identical pixel representation on any platform.
The QPainter class also provides a means of controlling the rendering quality through its RenderHint enum and the support for floating point precision: All the functions for drawing primitives has a floating point version. These are often used in combination with the QPainter::Antialiasing render hint.
The RenderHint enum specifies flags to QPainter that may or may not be respected by any given engine. QPainter::Antialiasing indicates that the engine should antialias edges of primitives if possible, QPainter::TextAntialiasing indicates that the engine should antialias text if possible, and the QPainter::SmoothPixmapTransform indicates that the engine should use a smooth pixmap transformation algorithm.
The renderHints() function returns a flag that specifies the rendering hints that are set for this painter. Use the setRenderHint() function to set or clear the currently set RenderHints.

painter.setWindow(-100,-100,1000,1000);//x`=(x*(widget::width()/1000)+100) in other words (0,0)->(-100,-100) (w,h)->(1000,1000)
painter.setViewport(100,100,1000,1000);//it is the oposit of setWindow x`=(x*1000/widget::width()+100) in other words (100,100)->(0,0) (1000,1000)->(w,h)

Coordinate Transformations

Normally, the QPainter operates on the device’s own coordinate system (usually pixels), but QPainter has good support for coordinate transformations.

noprotate()scale()translate()

The most commonly used transformations are scaling, rotation, translation and shearing. Use the scale() function to scale the coordinate system by a given offset, the rotate() function to rotate it clockwise and translate() to translate it (i.e. adding a given offset to the points). You can also twist the coordinate system around the origin using the shear() function.

The setWorldTransform() function can replace or add to the currently set worldTransform(). The resetTransform() function resets any transformations that were made using translate(), scale(), shear(), rotate(), setWorldTransform(), setViewport() and setWindow() functions. The deviceTransform() returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device. The latter function is only needed when using platform painting commands on the platform dependent handle, and the platform does not do transformations nativly.
When drawing with QPainter, we specify points using logical coordinates which then are converted into the physical coordinates of the paint device. The mapping of the logical coordinates to the physical coordinates are handled by QPainter’s combinedTransform(), a combination of viewport() and window() and worldTransform(). The viewport() represents the physical coordinates specifying an arbitrary rectangle, the window() describes the same rectangle in logical coordinates, and the worldTransform() is identical with the transformation matrix.

Clipping

QPainter can clip any drawing operation to a rectangle, a region, or a vector path. The current clip is available using the functions clipRegion() and clipPath(). Whether paths or regions are preferred (faster) depends on the underlying paintEngine(). For example, the QImage paint engine prefers paths while the X11 paint engine prefers regions. Setting a clip is done in the painters logical coordinates.
After QPainter’s clipping, the paint device may also clip. For example, most widgets clip away the pixels used by child widgets, and most printers clip away an area near the edges of the paper. This additional clipping is not reflected by the return value of clipRegion() or hasClipping().

QPainter::CompositionMode setCompositionMode

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.

painter.drawRect(QRect(0,0,300,300));
painter.setCompositionMode(QPainter::CompositionMode::CompositionMode_Difference);
painter.drawRect(QRect(0,0,500,500));

Painting Path

 painter path is an object composed of a number of graphical building blocks, such as rectangles, ellipses, lines, and curves. Building blocks can be joined in closed subpaths, for example as a rectangle or an ellipse. A closed path has coinciding start and end points. Or they can exist independently as unclosed subpaths, such as lines and curves.

A QPainterPath object can be used for filling, outlining, and clipping. To generate fillable outlines for a given painter path, use the QPainterPathStroker class. The main advantage of painter paths over normal drawing operations is that complex shapes only need to be created once; then they can be drawn many times using only calls to the QPainter::drawPath() function.

QPainterPath provides a collection of functions that can be used to obtain information about the path and its elements. In addition it is possible to reverse the order of the elements using the toReversed() function. There are also several functions to convert this painter path object into a polygon representation.

Composing a QPainterPath

A QPainterPath object can be constructed as an empty path, with a given start point, or as a copy of another QPainterPath object. Once created, lines and curves can be added to the path using the lineTo(), arcTo(), cubicTo() and quadTo() functions. The lines and curves stretch from the currentPosition() to the position passed as argument.

The currentPosition() of the QPainterPath object is always the end position of the last subpath that was added (or the initial start point). Use the moveTo() function to move the currentPosition() without adding a component. The moveTo() function implicitly starts a new subpath, and closes the previous one. Another way of starting a new subpath is to call the closeSubpath() function which closes the current path by adding a line from the currentPosition() back to the path’s start position. Note that the new path will have (0, 0) as its initial currentPosition().

QPainterPath class also provides several convenience functions to add closed subpaths to a painter path: addEllipse(), addPath(), addRect(), addRegion() and addText(). The addPolygon() function adds an unclosed subpath. In fact, these functions are all collections of moveTo(), lineTo() and cubicTo() operations.

In addition, a path can be added to the current path using the connectPath() function. But note that this function will connect the last element of the current path to the first element of given one by adding a line.

The painter path is initially empty when constructed. We first add a rectangle, which is a closed subpath. Then we add two bezier curves which together form a closed subpath even though they are not closed individually. Finally we draw the entire path. The path is filled using the default fill rule, Qt::OddEvenFill. Qt provides two methods for filling paths:

Qt::OddEvenFillQt::WindingFill

See the Qt::FillRule documentation for the definition of the rules. A painter path’s currently set fill rule can be retrieved using the fillRule() function, and altered using the setFillRule() function.

QPainterPath Information

The QPainterPath class provides a collection of functions that returns information about the path and its elements.
The currentPosition() function returns the end point of the last subpath that was added (or the initial start point). The elementAt() function can be used to retrieve the various subpath elements, the number of elements can be retrieved using the elementCount() function, and the isEmpty() function tells whether this QPainterPath object contains any elements at all.
The controlPointRect() function returns the rectangle containing all the points and control points in this path. This function is significantly faster to compute than the exact boundingRect() which returns the bounding rectangle of this painter path with floating point precision.
Finally, QPainterPath provides the contains() function which can be used to determine whether a given point or rectangle is inside the path, and the intersects() function which determines if any of the points inside a given rectangle also are inside this path.

QPainterPath Conversion

For compatibility reasons, it might be required to simplify the representation of a painter path: QPainterPath provides the toFillPolygon(), toFillPolygons() and toSubpathPolygons() functions which convert the painter path into a polygon. The toFillPolygon() returns the painter path as one single polygon, while the two latter functions return a list of polygons.
The toFillPolygons() and toSubpathPolygons() functions are provided because it is usually faster to draw several small polygons than to draw one large polygon, even though the total number of points drawn is the same. The difference between the two is the number of polygons they return: The toSubpathPolygons() creates one polygon for each subpath regardless of intersecting subpaths (i.e. overlapping bounding rectangles), while the toFillPolygons() functions creates only one polygon for overlapping subpaths.
The toFillPolygon() and toFillPolygons() functions first convert all the subpaths to polygons, then uses a rewinding technique to make sure that overlapping subpaths can be filled using the correct fill rule. Note that rewinding inserts additional lines in the polygon so the outline of the fill polygon does not match the outline of the path.

QLinearGradient myGradient;
QPen myPen;
QRectF boundingRectangle;

QPainterPath myPath;
myPath.addEllipse(boundingRectangle);

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
QPainterPath path;
path.addRect(20, 20, 60, 60);

path.moveTo(0, 0);
path.cubicTo(99, 0,  50, 50,  99, 99);
path.cubicTo(0, 99,  50, 50,  0, 0);

QPainter painter(this);
painter.fillRect(0, 0, 100, 100, Qt::white);
painter.setPen(QPen(QColor(79, 106, 25), 1, Qt::SolidLine,
                    Qt::FlatCap, Qt::MiterJoin));
painter.setBrush(QColor(122, 163, 39));

painter.drawPath(path);
QLinearGradient myGradient;
QPen myPen;
QPolygonF myPolygon;

QPainterPath myPath;
myPath.addPolygon(myPolygon);

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
QLinearGradient myGradient;
QPen myPen;
QRectF myRectangle;

QPainterPath myPath;
myPath.addRect(myRectangle);

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
QLinearGradient myGradient;
QPen myPen;
QFont myFont;
QPointF baseline(x, y);

QPainterPath myPath;
myPath.addText(baseline, myFont, tr("Qt"));

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
QLinearGradient myGradient;
QPen myPen;

QPointF center, startPoint;

QPainterPath myPath;
myPath.moveTo(center);
myPath.arcTo(boundingRect, startAngle,
             sweepLength);

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
QLinearGradient myGradient;
QPen myPen;

QPainterPath myPath;
myPath.cubicTo(c1, c2, endPoint);

QPainter painter(this);
painter.setBrush(myGradient);
painter.setPen(myPen);
painter.drawPath(myPath);
This image has an empty alt attribute; its file name is qpainterpath-construction.png

Qt Images And Fonts

Qt provides four classes for handling image data: QImageQPixmapQBitmap and QPicture. QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. QBitmap is only a convenience class that inherits QPixmap, ensuring a depth of 1. Finally, the QPicture class is a paint device that records and replays QPainter commands.

QImage

is a QPaintDevice subclass, QPainter can be used to draw directly onto images. When using QPainter on a QImage, the painting can be performed in another thread than the current GUI thread.

The QImage class supports several image formats described by the Format enum. These include monochrome, 8-bit, 32-bit and alpha-blended images which are available in all versions of Qt 4.x.

QImage provides a collection of functions that can be used to obtain a variety of information about the image. There are also several functions that enables transformation of the image.

QImage objects can be passed around by value since the QImage class uses implicit data sharing. QImage objects can also be streamed and compared.

Reading and Writing Image Files

QImage provides several ways of loading an image file: The file can be loaded when constructing the QImage object, or by using the load() or loadFromData() functions later on. QImage also provides the static fromData() function, constructing a QImage from the given data. When loading an image, the file name can either refer to an actual file on disk or to one of the application’s embedded resources. See The Qt Resource System overview for details on how to embed images and other resource files in the application’s executable.
Simply call the save() function to save a QImage object.

Image Information

QImage provides a collection of functions that can be used to obtain a variety of information about the image:

Available Functions
GeometryThe size(), width(), height(), dotsPerMeterX(), and dotsPerMeterY() functions provide information about the image size and aspect ratio.The rect() function returns the image’s enclosing rectangle. The valid() function tells if a given pair of coordinates is within this rectangle. The offset() function returns the number of pixels by which the image is intended to be offset by when positioned relative to other images, which also can be manipulated using the setOffset() function.
ColorsThe color of a pixel can be retrieved by passing its coordinates to the pixel() function. The pixel() function returns the color as a QRgb value indepedent of the image’s format.In case of monochrome and 8-bit images, the colorCount() and colorTable() functions provide information about the color components used to store the image data: The colorTable() function returns the image’s entire color table. To obtain a single entry, use the pixelIndex() function to retrieve the pixel index for a given pair of coordinates, then use the color() function to retrieve the color. Note that if you create an 8-bit image manually, you have to set a valid color table on the image as well.The hasAlphaChannel() function tells if the image’s format respects the alpha channel, or not. The allGray() and isGrayscale() functions tell whether an image’s colors are all shades of gray.See also the Pixel Manipulation and Image Transformations sections.
TextThe text() function returns the image text associated with the given text key. An image’s text keys can be retrieved using the textKeys() function. Use the setText() function to alter an image’s text.
Low-level informationThe depth() function returns the depth of the image. The supported depths are 1 (monochrome), 8, 16, 24 and 32 bits. The bitPlaneCount() function tells how many of those bits that are used. For more information see the Image Formats section.The format(), bytesPerLine(), and sizeInBytes() functions provide low-level information about the data stored in the image.The cacheKey() function returns a number that uniquely identifies the contents of this QImage object.

Pixel Manipulation

The functions used to manipulate an image’s pixels depend on the image format. The reason is that monochrome and 8-bit images are index-based and use a color lookup table, while 32-bit images store ARGB values directly. For more information on image formats, see the Image Formats section.

QImage image(3, 3, QImage::Format_RGB32);
QRgb value;

value = qRgb(189, 149, 39); // 0xffbd9527
image.setPixel(1, 1, value);

value = qRgb(122, 163, 39); // 0xff7aa327
image.setPixel(0, 1, value);
image.setPixel(1, 0, value);

value = qRgb(237, 187, 51); // 0xffedba31
image.setPixel(2, 1, value);
QImage image(3, 3, QImage::Format_Indexed8);
QRgb value;

value = qRgb(122, 163, 39); // 0xff7aa327
image.setColor(0, value);

value = qRgb(237, 187, 51); // 0xffedba31
image.setColor(1, value);

value = qRgb(189, 149, 39); // 0xffbd9527
image.setColor(2, value);

image.setPixel(0, 1, 0);
image.setPixel(1, 0, 0);
image.setPixel(1, 1, 2);
image.setPixel(2, 1, 1);

For images with more than 8-bit per color-channel. The methods setPixelColor() and pixelColor() can be used to set and get with QColor values.

QImage also provide the scanLine() function which returns a pointer to the pixel data at the scanline with the given index, and the bits() function which returns a pointer to the first pixel data (this is equivalent to scanLine(0)).

Image Formats

Each pixel stored in a QImage is represented by an integer. The size of the integer varies depending on the format. QImage supports several image formats described by the Format enum.

Monochrome images are stored using 1-bit indexes into a color table with at most two colors. There are two different types of monochrome images: big endian (MSB first) or little endian (LSB first) bit order.

8-bit images are stored using 8-bit indexes into a color table, i.e. they have a single byte per pixel. The color table is a QVector<QRgb>, and the QRgb typedef is equivalent to an unsigned int containing an ARGB quadruplet on the format 0xAARRGGBB.

32-bit images have no color table; instead, each pixel contains an QRgb value. There are three different types of 32-bit images storing RGB (i.e. 0xffRRGGBB), ARGB and premultiplied ARGB values respectively. In the premultiplied format the red, green, and blue channels are multiplied by the alpha component divided by 255.

An image’s format can be retrieved using the format() function. Use the convertToFormat() functions to convert an image into another format. The allGray() and isGrayscale() functions tell whether a color image can safely be converted to a grayscale image.

Image Transformations

QImage supports a number of functions for creating a new image that is a transformed version of the original: The createAlphaMask() function builds and returns a 1-bpp mask from the alpha buffer in this image, and the createHeuristicMask() function creates and returns a 1-bpp heuristic mask for this image. The latter function works by selecting a color from one of the corners, then chipping away pixels of that color starting at all the edges.
createMaskFromColor to get mask for specific color

The mirrored() function returns a mirror of the image in the desired direction, the scaled() returns a copy of the image scaled to a rectangle of the desired measures, and the rgbSwapped() function constructs a BGR image from a RGB image.

The scaledToWidth() and scaledToHeight() functions return scaled copies of the image.

The transformed() function returns a copy of the image that is transformed with the given transformation matrix and transformation mode: Internally, the transformation matrix is adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest image containing all transformed points of the original image. The static trueMatrix() function returns the actual matrix used for transforming the image.

There are also functions for changing attributes of an image in-place:

FunctionDescription
setDotsPerMeterX()Defines the aspect ratio by setting the number of pixels that fit horizontally in a physical meter.
setDotsPerMeterY()Defines the aspect ratio by setting the number of pixels that fit vertically in a physical meter.
fill()Fills the entire image with the given pixel value.
invertPixels()Inverts all pixel values in the image using the given InvertMode value.
setColorTable()Sets the color table used to translate color indexes. Only monochrome and 8-bit formats.
setColorCount()Resizes the color table. Only monochrome and 8-bit formats.

copy(QRect) to get copy image for specific region

QPixmap 

A QPixmap can easily be displayed on the screen using QLabel or one of QAbstractButton‘s subclasses (such as QPushButton and QToolButton). QLabel has a pixmap property, whereas QAbstractButton has an icon property.

QPixmap objects can be passed around by value since the QPixmap class uses implicit data sharing. For more information, see the Implicit Data Sharing documentation. QPixmap objects can also be streamed.

Note that the pixel data in a pixmap is internal and is managed by the underlying window system. Because QPixmap is a QPaintDevice subclass, QPainter can be used to draw directly onto pixmaps. Pixels can only be accessed through QPainter functions or by converting the QPixmap to a QImage. However, the fill() function is available for initializing the entire pixmap with a given color.

There are functions to convert between QImage and QPixmap. Typically, the QImage class is used to load an image file, optionally manipulating the image data, before the QImage object is converted into a QPixmap to be shown on screen. Alternatively, if no manipulation is desired, the image file can be loaded directly into a QPixmap.

and you can get pixmap from image by using fromImage static function.

Pixmap Information

QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap:

Available Functions
GeometryThe size(), width() and height() functions provide information about the pixmap’s size. The rect() function returns the image’s enclosing rectangle.
Alpha componentThe hasAlphaChannel() returns true if the pixmap has a format that respects the alpha channel, otherwise returns false. The hasAlpha(), setMask() and mask() functions are legacy and should not be used. They are potentially very slow.The createHeuristicMask() function creates and returns a 1-bpp heuristic mask (i.e. a QBitmap) for this pixmap. It works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges. The createMaskFromColor() function creates and returns a mask (i.e. a QBitmap) for the pixmap based on a given color.
Low-level informationThe depth() function returns the depth of the pixmap. The defaultDepth() function returns the default depth, i.e. the depth used by the application on the given screen.The cacheKey() function returns a number that uniquely identifies the contents of the QPixmap object.

Pixmap Conversion

A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap::fromImage() instead.

To convert a QPixmap to and from HICON you can use the QtWinExtras functions QtWin::toHICON() and QtWin::fromHICON() respectively.

Pixmap Transformations

QPixmap supports a number of functions for creating a new pixmap that is a transformed version of the original:

The scaled(), scaledToWidth() and scaledToHeight() functions return scaled copies of the pixmap, while the copy() function creates a QPixmap that is a plain copy of the original one.

The transformed() function returns a copy of the pixmap that is transformed with the given transformation matrix and transformation mode: Internally, the transformation matrix is adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest pixmap containing all transformed points of the original pixmap. The static trueMatrix() function returns the actual matrix used for transforming the pixmap.

//heuristic mask
QPixmap myPixmap;
myPixmap.setMask(myPixmap.createHeuristicMask());
//save pixmap
QPixmap pixmap;
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format
//scroll pixels
QLabel label;
QPixmap pixmap("C:/Users/moham/OneDrive/Pictures/Capture.PNG");
pixmap.scroll(100,100,QRect(100,100,400,400));//copy rect and offset it
label.setPixmap(pixmap);
label.show();
//transform
QLabel label;
QPixmap pixmap("C:/Users/moham/OneDrive/Pictures/Capture.PNG");
QPixmap pixmap2=pixmap.transformed(QTransform::fromScale(2,2));
label.setPixmap(pixmap2);
label.show();

QFont , QFontMetric

QFont can be regarded as a query for one or more fonts on the system.

When you create a QFont object you specify various attributes that you want the font to have. Qt will use the font with the specified attributes, or if no matching font exists, Qt will use the closest matching installed font. The attributes of the font that is actually used are retrievable from a QFontInfo object. If the window system provides an exact match exactMatch() returns true. Use QFontMetricsF to get measurements, e.g. the pixel length of a string using QFontMetrics::width().

Attributes which are not specifically set will not affect the font selection algorithm, and default values will be preferred instead.

To load a specific physical font, typically represented by a single file, use QRawFont instead.

Note that a QGuiApplication instance must exist before a QFont can be used. You can set the application’s default font with QGuiApplication::setFont().

If a chosen font does not include all the characters that need to be displayed, QFont will try to find the characters in the nearest equivalent fonts. When a QPainter draws a character from a font the QFont will report whether or not it has the character; if it does not, QPainter will draw an unfilled square.

QFont serifFont("Times", 10, QFont::Bold);
QFont sansFont("Helvetica [Cronyx]", 12);

The attributes set in the constructor can also be set later, e.g. setFamily(), setPointSize(), setPointSizeF(), setWeight() and setItalic(). The remaining attributes must be set after contstruction, e.g. setBold(), setUnderline(), setOverline(), setStrikeOut() and setFixedPitch(). QFontInfo objects should be created after the font’s attributes have been set. A QFontInfo object will not change, even if you change the font’s attributes. The corresponding “get” functions, e.g. family(), pointSize(), etc., return the values that were set, even though the values used may differ. The actual values are available from a QFontInfo object.

If the requested font family is unavailable you can influence the font matching algorithm by choosing a particular QFont::StyleHint and QFont::StyleStrategy with setStyleHint(). The default family (corresponding to the current style hint) is returned by defaultFamily().

You can provide substitutions for font family names using insertSubstitution() and insertSubstitutions(). Substitutions can be removed with removeSubstitutions(). Use substitute() to retrieve a family’s first substitute, or the family name itself if it has no substitutes. Use substitutes() to retrieve a list of a family’s substitutes (which may be empty). After substituting a font, you must trigger the updating of the font by destroying and re-creating all QFont objects.

Every QFont has a key() which you can use, for example, as the key in a cache or dictionary. If you want to store a user’s font preferences you could use QSettings, writing the font information with toString() and reading it back with fromString(). The operator<<() and operator>>() functions are also available, but they work on a data stream.

It is possible to set the height of characters shown on the screen to a specified number of pixels with setPixelSize(); however using setPointSize() has a similar effect and provides device independence.

The font matching algorithm works as follows:

  1. The specified font families (set by setFamilies()) are searched for.
  2. If not found, then if set the specified font family exists and can be used to represent the writing system in use, it will be selected.
  3. If not, a replacement font that supports the writing system is selected. The font matching algorithm will try to find the best match for all the properties set in the QFont. How this is done varies from platform to platform.
  4. If no font exists on the system that can support the text, then special “missing character” boxes will be shown in its place.

Note: If the selected font, though supporting the writing system in general, is missing glyphs for one or more specific characters, then Qt will try to find a fallback font for this or these particular characters. This feature can be disabled using QFont::NoFontMerging style strategy.

In Windows a request for the “Courier” font is automatically changed to “Courier New”, an improved version of Courier that allows for smooth scaling. The older “Courier” bitmap font can be selected by setting the PreferBitmap style strategy (see setStyleStrategy()).

Once a font is found, the remaining attributes are matched in order of priority:

  1. fixedPitch()
  2. pointSize() (see below)
  3. weight()
  4. style()

If you have a font which matches on family, even if none of the other attributes match, this font will be chosen in preference to a font which doesn’t match on family but which does match on the other attributes. This is because font family is the dominant search criteria.

The point size is defined to match if it is within 20% of the requested point size. When several fonts match and are only distinguished by point size, the font with the closest point size to the one requested will be chosen.

The actual family, font size, weight and other font attributes used for drawing text will depend on what’s available for the chosen family under the window system. A QFontInfo object can be used to determine the actual values used for drawing the text.

QFontMetrics fm(f1);
int textWidthInPixels = fm.horizontalAdvance("How many pixels wide is this text?");
int textHeightInPixels = fm.height();
QRect rect = fm.boundingRect("hello");

QFontDatabase : The most common uses of this class are to query the database for the list of font families() and for the pointSizes() and styles() that are available for each family. An alternative to pointSizes() is smoothSizes() which returns the sizes at which a given family and style will look attractive.
addApplicationFont , addApplicationFontFromData to load font file

Widgets in Qt

The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it.

A widget that is not embedded in a parent widget is called a window. Usually, windows have a frame and a title bar, although it is also possible to create windows without such decoration using suitable window flags). In Qt, QMainWindow and the various subclasses of QDialog are the most common window types.

Every widget’s constructor accepts one or two standard arguments:

  1. QWidget *parent = nullptr is the parent of the new widget. If it is nullptr (the default), the new widget will be a window. If not, it will be a child of parent, and be constrained by parent‘s geometry (unless you specify Qt::Window as window flag).
  2. Qt::WindowFlags f = { } (where available) sets the window flags; the default is suitable for almost all widgets, but to get, for example, a window without a window system frame, you must use special flags.

QWidget has many member functions, but some of them have little direct functionality; for example, QWidget has a font property, but never uses this itself. There are many subclasses which provide real functionality, such as QLabelQPushButtonQListWidget, and QTabWidget.

Top-Level and Child Widgets

A widget without a parent widget is always an independent window (top-level widget). For these widgets, setWindowTitle() and setWindowIcon() set the title bar and icon respectively.

Non-window widgets are child widgets, displayed within their parent widgets. Most widgets in Qt are mainly useful as child widgets. For example, it is possible to display a button as a top-level window, but most people prefer to put their buttons inside other widgets, such as QDialog.

A parent widget containing various child widgets.

The diagram above shows a QGroupBox widget being used to hold various child widgets in a layout provided by QGridLayout. The QLabel child widgets have been outlined to indicate their full sizes.

If you want to use a QWidget to hold child widgets you will usually want to add a layout to the parent QWidget. See Layout Management for more information.

Composite Widgets

When a widget is used as a container to group a number of child widgets, it is known as a composite widget. These can be created by constructing a widget with the required visual properties – a QFrame, for example – and adding child widgets to it, usually managed by a layout. The above diagram shows such a composite widget that was created using Qt Designer.

Composite widgets can also be created by subclassing a standard widget, such as QWidget or QFrame, and adding the necessary layout and child widgets in the constructor of the subclass. Many of the examples provided with Qt use this approach, and it is also covered in the Qt Tutorials.

Custom Widgets and Painting

Since QWidget is a subclass of QPaintDevice, subclasses can be used to display custom content that is composed using a series of painting operations with an instance of the QPainter class. This approach contrasts with the canvas-style approach used by the Graphics View Framework where items are added to a scene by the application and are rendered by the framework itself.

Each widget performs all painting operations from within its paintEvent() function. This is called whenever the widget needs to be redrawn, either as a result of some external change or when requested by the application.

Size Hints and Size Policies

When implementing a new widget, it is almost always useful to reimplement sizeHint() to provide a reasonable default size for the widget and to set the correct size policy with setSizePolicy().

By default, composite widgets which do not provide a size hint will be sized according to the space requirements of their child widgets.

The size policy lets you supply good default behavior for the layout management system, so that other widgets can contain and manage yours easily. The default size policy indicates that the size hint represents the preferred size of the widget, and this is often good enough for many widgets.

Events

Widgets respond to events that are typically caused by user actions. Qt delivers events to widgets by calling specific event handler functions with instances of QEvent subclasses containing information about each event.

If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child’s underMouse() function inside the widget’s mousePressEvent().

The Scribble example implements a wider set of events to handle mouse movement, button presses, and window resizing.

You will need to supply the behavior and content for your own widgets, but here is a brief overview of the events that are relevant to QWidget, starting with the most common ones:

  • paintEvent() is called whenever the widget needs to be repainted. Every widget displaying custom content must implement it. Painting using a QPainter can only take place in a paintEvent() or a function called by a paintEvent().
  • resizeEvent() is called when the widget has been resized.
  • mousePressEvent() is called when a mouse button is pressed while the mouse cursor is inside the widget, or when the widget has grabbed the mouse using grabMouse(). Pressing the mouse without releasing it is effectively the same as calling grabMouse().
  • mouseReleaseEvent() is called when a mouse button is released. A widget receives mouse release events when it has received the corresponding mouse press event. This means that if the user presses the mouse inside your widget, then drags the mouse somewhere else before releasing the mouse button, your widget receives the release event. There is one exception: if a popup menu appears while the mouse button is held down, this popup immediately steals the mouse events.
  • mouseDoubleClickEvent() is called when the user double-clicks in the widget. If the user double-clicks, the widget receives a mouse press event, a mouse release event, (a mouse click event,) a second mouse press, this event and finally a second mouse release event. (Some mouse move events may also be received if the mouse is not held steady during this operation.) It is not possible to distinguish a click from a double-click until the second click arrives. (This is one reason why most GUI books recommend that double-clicks be an extension of single-clicks, rather than trigger a different action.)

Widgets that accept keyboard input need to reimplement a few more event handlers:

  • keyPressEvent() is called whenever a key is pressed, and again when a key has been held down long enough for it to auto-repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event().
  • focusInEvent() is called when the widget gains keyboard focus (assuming you have called setFocusPolicy()). Well-behaved widgets indicate that they own the keyboard focus in a clear but discreet way.
  • focusOutEvent() is called when the widget loses keyboard focus.

You may be required to also reimplement some of the less common event handlers:

  • mouseMoveEvent() is called whenever the mouse moves while a mouse button is held down. This can be useful during drag and drop operations. If you call setMouseTracking(true), you get mouse move events even when no buttons are held down. (See also the Drag and Drop guide.)
  • keyReleaseEvent() is called whenever a key is released and while it is held down (if the key is auto-repeating). In that case, the widget will receive a pair of key release and key press event for every repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event().
  • wheelEvent() is called whenever the user turns the mouse wheel while the widget has the focus.
  • enterEvent() is called when the mouse enters the widget’s screen space. (This excludes screen space owned by any of the widget’s children.)
  • leaveEvent() is called when the mouse leaves the widget’s screen space. If the mouse enters a child widget it will not cause a leaveEvent().
  • moveEvent() is called when the widget has been moved relative to its parent.
  • closeEvent() is called when the user closes the widget (or when close() is called).

Groups of Functions and Properties

ContextFunctions and Properties
Window functionsshow(), hide(), raise(), lower(), close().
Top-level windowswindowModifiedwindowTitlewindowIcon,
 isActiveWindowactivateWindow(), minimized,
 showMinimized(), maximizedshowMaximized(),
 fullScreenshowFullScreen(), showNormal().
Window contentsupdate(), repaint(), scroll(),setContentsMargins().
Geometryposx(), y(), rectsizewidth(), height(), move(), resize(), 
sizePolicysizeHint(), minimumSizeHint(), updateGeometry(),
 layout(), frameGeometrygeometrychildrenRect,
 childrenRegionadjustSize(), mapFromGlobal(), 
mapToGlobal(), mapFromParent(), mapToParent(), 
maximumSizeminimumSizesizeIncrementbaseSize,
 setFixedSize(),childAt(QPoint)
ModevisibleisVisibleTo(), enabledisEnabledTo(), modal,
 isWindow(), mouseTrackingupdatesEnabledvisibleRegion().
Look and feelstyle(), setStyle(), styleSheetcursorfontpalette,
 backgroundRole(), setBackgroundRole(), fontInfo(),
 fontMetrics().
Keyboard focus functionsfocusfocusPolicysetFocus(), clearFocus(), setTabOrder(), 
setFocusProxy(), focusNextChild(), focusPreviousChild().
Mouse and keyboard grabbinggrabMouse(), releaseMouse(), grabKeyboard(), 
releaseKeyboard(), mouseGrabber(), keyboardGrabber(),
grabShortcut().
Event handlersevent(), mousePressEvent(), mouseReleaseEvent(),
 mouseDoubleClickEvent(), mouseMoveEvent(),
 keyPressEvent(), keyReleaseEvent(), focusInEvent(),
 focusOutEvent(), wheelEvent(), enterEvent(), leaveEvent(),
 paintEvent(), moveEvent(), resizeEvent(), closeEvent(), 
dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(), 
dropEvent(), childEvent(), showEvent(), hideEvent(), 
customEvent(). changeEvent(),
System functionsparentWidget(), window(), setParent(), winId(), find(),
 metric().
Context menucontextMenuPolicycontextMenuEvent(),
 customContextMenuRequested(), actions()
Interactive helpsetToolTip(), setWhatsThis()

Horizontal, Vertical, Grid, and Form Layouts

The easiest way to give your widgets a good layout is to use the built-in layout managers: QHBoxLayoutQVBoxLayoutQGridLayout, QStackedLayout and QFormLayout. These classes inherit from QLayout, which in turn derives from QObject (not QWidget). They take care of geometry management for a set of widgets. To create more complex layouts, you can nest layout managers inside each other.

  • QHBoxLayout lays out widgets in a horizontal row, from left to right (or right to left for right-to-left languages).
  • QVBoxLayout lays out widgets in a vertical column, from top to bottom.
  • QGridLayout lays out widgets in a two-dimensional grid. Widgets can occupy multiple cells.
  • QFormLayout lays out widgets in a 2-column descriptive label- field style.
QWidget *window = new QWidget;
    QPushButton *button1 = new QPushButton("One");
    QPushButton *button2 = new QPushButton("Two");
    QPushButton *button3 = new QPushButton("Three");
    QPushButton *button4 = new QPushButton("Four");
    QPushButton *button5 = new QPushButton("Five");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    layout->addWidget(button4);
    layout->addWidget(button5);

    window->setLayout(layout);
    window->show();
QWidget *window = new QWidget;
    QPushButton *button1 = new QPushButton("One");
    QPushButton *button2 = new QPushButton("Two");
    QPushButton *button3 = new QPushButton("Three");
    QPushButton *button4 = new QPushButton("Four");
    QPushButton *button5 = new QPushButton("Five");

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(button1, 0, 0);
    layout->addWidget(button2, 0, 1);
    layout->addWidget(button3, 1, 0, 1, 2);
    layout->addWidget(button4, 2, 0);
    layout->addWidget(button5, 2, 1);

    window->setLayout(layout);
    window->show();
QWidget *window = new QWidget;
    QPushButton *button1 = new QPushButton("One");
    QLineEdit *lineEdit1 = new QLineEdit();
    QPushButton *button2 = new QPushButton("Two");
    QLineEdit *lineEdit2 = new QLineEdit();
    QPushButton *button3 = new QPushButton("Three");
    QLineEdit *lineEdit3 = new QLineEdit();

    QFormLayout *layout = new QFormLayout;
    layout->addRow(button1, lineEdit1);
    layout->addRow(button2, lineEdit2);
    layout->addRow(button3, lineEdit3);

    window->setLayout(layout);
    window->show();

Note: Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.

You can nest layouts using addLayout() on a layout; the inner layout then becomes a child of the layout it is inserted into.

Adding Widgets to a Layout

When you add widgets to a layout, the layout process works as follows:

  1. All the widgets will initially be allocated an amount of space in accordance with their QWidget::sizePolicy() and QWidget::sizeHint().
  2. If any of the widgets have stretch factors set, with a value greater than zero, then they are allocated space in proportion to their stretch factor (explained below).
  3. If any of the widgets have stretch factors set to zero they will only get more space if no other widgets want the space. Of these, space is allocated to widgets with an Expanding size policy first.
  4. Any widgets that are allocated less space than their minimum size (or minimum size hint if no minimum size is specified) are allocated this minimum size they require. (Widgets don’t have to have a minimum size or minimum size hint in which case the stretch factor is their determining factor.)
  5. Any widgets that are allocated more space than their maximum size are allocated the maximum size space they require. (Widgets do not have to have a maximum size in which case the stretch factor is their determining factor.)

Stretch Factors

Widgets are normally created without any stretch factor set. When they are laid out in a layout the widgets are given a share of space in accordance with their QWidget::sizePolicy() or their minimum size hint whichever is the greater. Stretch factors are used to change how much space widgets are given in proportion to one another.

If we have three widgets laid out using a QHBoxLayout with no stretch factors set we will get a layout like this:

Three widgets in a row

If we apply stretch factors to each widget, they will be laid out in proportion (but never less than their minimum size hint), e.g.

Three widgets with different stretch factors in a row

Custom Widgets in Layouts

When you make your own widget class, you should also communicate its layout properties. If the widget uses one of Qt’s layouts, this is already taken care of. If the widget does not have any child widgets, or uses a manual layout, you can change the behavior of the widget using any or all of the following mechanisms:

Call QWidget::updateGeometry() whenever the size hint, minimum size hint or size policy changes. This will cause a layout recalculation. Multiple consecutive calls to QWidget::updateGeometry() will only cause one layout recalculation.

If the preferred height of your widget depends on its actual width (e.g., a label with automatic word-breaking), set the height-for-width flag in the widget’s size policy and reimplement QWidget::heightForWidth().

Even if you implement QWidget::heightForWidth(), it is still a good idea to provide a reasonable sizeHint().

For further guidance when implementing these functions, see the Qt Quarterly article Trading Height for Width.

indexOf , itemAt , setAlignment , setContentsMargins , setSizeConstraint , setSpacing , takeAt
for boxlayout
addSpacing , addStretch , setDirection , addStrut and you can use insert instead of add to determine the index

size hint

class TObject1:public QFrame
{
    Q_OBJECT
public:
    explicit TObject1(QWidget* obj=nullptr):QFrame(obj)
    {
        this->setMouseTracking(true);// tracking cursor without press
        this->setStyleSheet("background-color: black");
        this->setMaximumSize(900,300);
    }
    void mouseMoveEvent(QMouseEvent *event) override{
        event->setAccepted(true);// don't move event to parent
    }
    QSize sizeHint() const override{//default size
        return QSize(600,200);
    }
    QSize minimumSizeHint() const override{// minimum size
        return QSize(300,100);
    }
};

QWidget w;
QVBoxLayout vb(&w);
TObject1 to1,to2;
to1.setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);//fixed vertical to size hint
to2.setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);//fixed vertical to size hint
vb.addWidget(&to1,Qt::AlignLeft);
vb.setSizeConstraint(QLayout::SetDefaultConstraint);
QSpacerItem si(100,100,QSizePolicy::Policy::Expanding,QSizePolicy::Policy::Expanding);
vb.addSpacerItem(&si);
vb.addWidget(&to2,Qt::AlignLeft);
w.show();

size policy


QWidget w;
QVBoxLayout vb(&w);
TObject1 to1,to2;
QSizePolicy policy1(QSizePolicy::Expanding,QSizePolicy::Expanding),policy2(QSizePolicy::Expanding,QSizePolicy::Expanding);
policy1.setVerticalStretch(1);
policy2.setVerticalStretch(2);
to1.setSizePolicy(policy1);
to2.setSizePolicy(policy2);
QSpacerItem si(100,100,QSizePolicy::Policy::Fixed,QSizePolicy::Policy::Fixed);
vb.addSpacerItem(&si);
vb.addWidget(&to1);
vb.addWidget(&to2);
w.show();

Most important functions in QSizePolicy
setControlType , setRetainSizeWhenHidden , transpose

isVisibleTo


QFrame frame1,frame2(&frame1),frame3(&frame2),frame4(&frame3);
frame2.hide();
qDebug()<<frame4.isVisibleTo(&frame1);//false
qDebug()<<frame4.isVisibleTo(&frame3);//true
//window id 
QFrame frame1,frame2(&frame1),frame3(&frame2),frame4(&frame3);
qDebug()<<(frame4.window()->winId()==frame1.winId());//true
frame1.find(frame4.winId()).hide();
//widget scroll you can use QScrollArea instead
QWidget frame1;
QLabel label1(" one ",&frame1), label2(" two ",&frame1), label3(" three ",&frame1);
label1.setGeometry(50,50,100,100);
label2.setGeometry(200,50,100,100);
label3.setGeometry(350,50,100,100);
frame1.resize(200,200);
frame1.show();
frame1.scroll(-120,0);//scroll right
void mousePressEvent(QMouseEvent *event) override{
   qDebug()<<"press on it";
}
QWidget frame1;
QPushButton button1(" one ",&frame1), button2(" two ",&frame1), button3(" three ",&frame1);
TObject1 to(&frame1);
button1.setGeometry(50,50,100,100);
button2.setGeometry(200,50,100,100);
button3.setGeometry(350,50,100,100);
to.setGeometry(500,50,100,100);
to.grabMouse();//buttons never take any mouse events all events grabbed by to

note : if you want to take QPixmap for widget use grab

I/O In Qt

Qt encapsulates the more generalized notion of byte streams in its QIODevice class, which is the parent class for QFile, as well as network I/O classes such as QTcpSocket. We don’t directly create a QIODevice instance, of course, but instead create something such as a QFile subclass and then work with the QFile instance directly to read from and write to the file.

Before accessing the device, open() must be called to set the correct OpenMode (such as ReadOnly or ReadWrite). You can then write to the device with write() or putChar(), and read by calling either read(), readLine(), or readAll(). Call close() when you are done with the device.

QIODevice distinguishes between two types of devices: random-access devices and sequential devices.

  • Random-access devices support seeking to arbitrary positions using seek(). The current position in the file is available by calling pos(). QFile and QBuffer are examples of random-access devices.
  • Sequential devices don’t support seeking to arbitrary positions. The data must be read in one pass. The functions pos() and size() don’t work for sequential devices. QTcpSocket and QProcess are examples of sequential devices.

You can use isSequential() to determine the type of device.

QIODevice emits readyRead() when new data is available for reading; for example, if new data has arrived on the network or if additional data is appended to a file that you are reading from. You can call bytesAvailable() to determine the number of bytes that are currently available for reading. It’s common to use bytesAvailable() together with the readyRead() signal when programming with asynchronous devices such as QTcpSocket, where fragments of data can arrive at arbitrary points in time. QIODevice emits the bytesWritten() signal every time a payload of data has been written to the device. Use bytesToWrite() to determine the current amount of data waiting to be written.

Certain subclasses of QIODevice, such as QTcpSocket and QProcess, are asynchronous. This means that I/O functions such as write() or read() always return immediately, while communication with the device itself may happen when control goes back to the event loop. QIODevice provides functions that allow you to force these operations to be performed immediately, while blocking the calling thread and without entering the event loop. This allows QIODevice subclasses to be used without an event loop, or in a separate thread:

  • waitForReadyRead() – This function suspends operation in the calling thread until new data is available for reading.
  • waitForBytesWritten() – This function suspends operation in the calling thread until one payload of data has been written to the device.
  • waitFor….() – Subclasses of QIODevice implement blocking functions for device-specific operations. For example, QProcess has a function called waitForStarted() which suspends operation in the calling thread until the process has started.

Calling these functions from the main, GUI thread, may cause your user interface to freeze. Example:

QProcess gzip;
gzip.start("gzip", QStringList() << "-c");
if (!gzip.waitForStarted())
    return false;

gzip.write("uncompressed data");

QByteArray compressed;
while (gzip.waitForReadyRead())
    compressed += gzip.readAll();

By subclassing QIODevice, you can provide the same interface to your own I/O devices. Subclasses of QIODevice are only required to implement the protected readData() and writeData() functions. QIODevice uses these functions to implement all its convenience functions, such as getChar(), readLine() and write(). QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData() is called.

Some subclasses, such as QFile and QTcpSocket, are implemented using a memory buffer for intermediate storing of data. This reduces the number of required device accessing calls, which are often very slow. Buffering makes functions like getChar() and putChar() fast, as they can operate on the memory buffer instead of directly on the device itself. Certain I/O operations, however, don’t work well with a buffer. For example, if several users open the same device and read it character by character, they may end up reading the same data when they meant to read a separate chunk each. For this reason, QIODevice allows you to bypass any buffering by passing the Unbuffered flag to open(). When subclassing QIODevice, remember to bypass any buffer you may use when the device is open in Unbuffered mode.

Some sequential devices support communicating via multiple channels. These channels represent separate streams of data that have the property of independently sequenced delivery. Once the device is opened, you can determine the number of channels by calling the readChannelCount() and writeChannelCount() functions. To switch between channels, call setCurrentReadChannel() and setCurrentWriteChannel(), respectively. QIODevice also provides additional signals to handle asynchronous communication on a per-channel basis.

Multithreading With Qt

QThread

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

class MyThread : public QThread 
{ 
    Q_OBJECT 
    void run() Q_DECL_OVERRIDE
    { 
        /* perform the expensive operation */ 
    } 
}; 
 
void MyObject::startWorkInAThread() 
{ 
    MyThread *myThread = new MyThread(this); 
    connect(myThread, &MyObject::threadFinished, this, 
        MyObject::notifyThreadFinished); 
    connect(myThread, &MyThread::finished, myThread, 
        &QObject::deleteLater); 
    myThread->start(); 
}

You can use worker objects by moving them to the thread using QObject::moveToThread().

class Worker : public QObject
{
    Q_OBJECT

public slots:
    void doWork(const QString ¶meter) {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }

signals:
    void resultReady(const QString &result);
};

class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
        connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
        connect(this, &Controller::operate, worker, &Worker::doWork);
        connect(worker, &Worker::resultReady, this, &Controller::handleResults);
        workerThread.start();
    }
    ~Controller() {
        workerThread.quit();
        workerThread.wait();
    }
public slots:
    void handleResults(const QString &);
signals:
    void operate(const QString &);
};

The code inside the Worker’s slot would then execute in a separate thread. However, you are free to connect the Worker’s slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.

class WorkerThread : public QThread
{
    Q_OBJECT
    void run() override {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }
signals:
    void resultReady(const QString &s);
};

void MyObject::startWorkInAThread()
{
    WorkerThread *workerThread = new WorkerThread(this);
    connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
    connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
    workerThread->start();
}

In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().

Managing Threads

QThread will notifiy you via a signal when the thread is started() and finished(), or you can use isFinished() and isRunning() to query the state of the thread.

You can stop the thread by calling exit() or quit(). In extreme cases, you may want to forcibly terminate() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for terminate() and setTerminationEnabled() for detailed information.

From Qt 4.8 onwards, it is possible to deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater().

Use wait() to block the calling thread, until the other thread has finished execution (or until a specified time has passed).

QThread also provides static, platform independent sleep functions: sleep(), msleep(), and usleep() allow full second, millisecond, and microsecond resolution respectively. These functions were made public in Qt 5.0.

Note: wait() and the sleep() functions should be unnecessary in general, since Qt is an event-driven framework. Instead of wait(), consider listening for the finished() signal. Instead of the sleep() functions, consider using QTimer.

The static functions currentThreadId() and currentThread() return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a QThread pointer.

To choose the name that your thread will be given (as identified by the command ps -L on Linux, for example), you can call setObjectName() before starting the thread. If you don’t call setObjectName(), the name given to your thread will be the class name of the runtime type of your thread object (for example, "RenderThread" in the case .

QThreadPool

QThreadPool manages and recyles individual QThread objects to help reduce thread creation costs in programs that use threads. Each Qt application has one global QThreadPool object, which can be accessed by calling globalInstance().

To use one of the QThreadPool threads, subclass QRunnable and implement the run() virtual function. Then create an object of that class and pass it to QThreadPool::start().

class HelloWorldTask : public QRunnable
{
    void run() override
    {
        qDebug() << "Hello world from thread" << QThread::currentThread();
    }
};

HelloWorldTask *hello = new HelloWorldTask();
// QThreadPool takes ownership and deletes 'hello' automatically
QThreadPool::globalInstance()->start(hello);

QThreadPool deletes the QRunnable automatically by default. Use QRunnable::setAutoDelete() to change the auto-deletion flag.

QThreadPool supports executing the same QRunnable more than once by calling tryStart(this) from within QRunnable::run(). If autoDelete is enabled the QRunnable will be deleted when the last thread exits the run function. Calling start() multiple times with the same QRunnable when autoDelete is enabled creates a race condition and is not recommended.

Threads that are unused for a certain amount of time will expire. The default expiry timeout is 30000 milliseconds (30 seconds). This can be changed using setExpiryTimeout(). Setting a negative expiry timeout disables the expiry mechanism.

Call maxThreadCount() to query the maximum number of threads to be used. If needed, you can change the limit with setMaxThreadCount(). The default maxThreadCount() is QThread::idealThreadCount(). The activeThreadCount() function returns the number of threads currently doing work.

The reserveThread() function reserves a thread for external use. Use releaseThread() when your are done with the thread, so that it may be reused. Essentially, these functions temporarily increase or reduce the active thread count and are useful when implementing time-consuming operations that are not visible to the QThreadPool.

Note that QThreadPool is a low-level class for managing threads, see the Qt Concurrent module for higher level alternatives.

note: you can create runnable object by QRunnable::create(std::function<void ()> functionToRun)

Mutex and Recursive Mutix

it is very similar to c++ mutex

QMutex mutex;
int number = 6;

void method1()
{
    mutex.lock();
    number *= 5;
    number /= 4;
    mutex.unlock();
}

void method2()
{
    mutex.lock();
    number *= 3;
    number /= 2;
    mutex.unlock();
}

Then only one thread can modify number at any given time and the result is correct. This is a trivial example, of course, but applies to any other case where things need to happen in a particular sequence.

When you call lock() in a thread, other threads that try to call lock() in the same place will block until the thread that got the lock calls unlock(). A non-blocking alternative to lock() is tryLock().

QMutex is optimized to be fast in the non-contended case. A non-recursive QMutex will not allocate memory if there is no contention on that mutex. It is constructed and destroyed with almost no overhead, which means it is fine to have many mutexes as part of other classes.

The QRecursiveMutex class is a mutex, like QMutex, with which it is API-compatible. It differs from QMutex by accepting lock() calls from the same thread any number of times. QMutex would deadlock in this situation.

QRecursiveMutex is much more expensive to construct and operate on, so use a plain QMutex whenever you can. 

int complexFunction(int flag)
{
    QMutexLocker locker(&mutex);

    int retVal = 0;

    switch (flag) {
    case 0:
    case 1:
        return moreComplexFunction(flag);
    case 2:
        {
            int status = anotherFunction();
            if (status < 0)
                return -2;
            retVal = status + flag;
        }
        break;
    default:
        if (flag > 10)
            return -1;
        break;
    }

    return retVal;
}

QMutexLocker is similar to c++ std::unique_lock

QReadWriteLock lock;

void ReaderThread::run()
{
    ...
    lock.lockForRead();
    read_file();
    lock.unlock();
    ...
}

void WriterThread::run()
{
    ...
    lock.lockForWrite();
    write_file();
    lock.unlock();
    ...
}

A read-write lock is a synchronization tool for protecting resources that can be accessed for reading and writing. This type of lock is useful if you want to allow multiple threads to have simultaneous read-only access, but as soon as one thread wants to write to the resource, all other threads must be blocked until the writing is complete.

In many cases, QReadWriteLock is a direct competitor to QMutex. QReadWriteLock is a good choice if there are many concurrent reads and writing occurs infrequently.

QSemaphore 

A semaphore is a generalization of a mutex. While a mutex can only be locked once, it’s possible to acquire a semaphore multiple times. Semaphores are typically used to protect a certain number of identical resources.

Semaphores support two fundamental operations, acquire() and release():

  • acquire(n) tries to acquire n resources. If there aren’t that many resources available, the call will block until this is the case.
  • release(n) releases n resources.

There’s also a tryAcquire() function that returns immediately if it cannot acquire the resources, and an available() function that returns the number of available resources at any time.

QSemaphore sem(5);      // sem.available() == 5

sem.acquire(3);         // sem.available() == 2
sem.acquire(2);         // sem.available() == 0
sem.release(5);         // sem.available() == 5
sem.release(5);         // sem.available() == 10

sem.tryAcquire(1);      // sem.available() == 9, returns true
sem.tryAcquire(250);    // sem.available() == 9, returns false

https://doc.qt.io/qt-5/qtcore-threads-semaphores-example.html

Wait Conditions

const int DataSize = 100000;

const int BufferSize = 8192;
char buffer[BufferSize];

QWaitCondition bufferNotEmpty;
QWaitCondition bufferNotFull;
QMutex mutex;
int numUsedBytes = 0;
class Producer : public QThread
{
public:
    Producer(QObject *parent = NULL) : QThread(parent)
    {
    }

    void run() override
    {
        for (int i = 0; i < DataSize; ++i) {
            mutex.lock();
            if (numUsedBytes == BufferSize)
                bufferNotFull.wait(&mutex);
            mutex.unlock();

            buffer[i % BufferSize] = "ACGT"[QRandomGenerator::global()->bounded(4)];

            mutex.lock();
            ++numUsedBytes;
            bufferNotEmpty.wakeAll();
            mutex.unlock();
        }
    }
};
class Consumer : public QThread
{
    Q_OBJECT
public:
    Consumer(QObject *parent = NULL) : QThread(parent)
    {
    }

    void run() override
    {
        for (int i = 0; i < DataSize; ++i) {
            mutex.lock();
            if (numUsedBytes == 0)
                bufferNotEmpty.wait(&mutex);
            mutex.unlock();

            fprintf(stderr, "%c", buffer[i % BufferSize]);

            mutex.lock();
            --numUsedBytes;
            bufferNotFull.wakeAll();
            mutex.unlock();
        }
        fprintf(stderr, "\n");
    }

signals:
    void stringConsumed(const QString &text);
};
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    Producer producer;
    Consumer consumer;
    producer.start();
    consumer.start();
    producer.wait();
    consumer.wait();
    return 0;
}

Thread safety vs Reentrancy

class Counter
{
public:
    Counter() { n = 0; }

    void increment() { ++n; }
    void decrement() { --n; }
    int value() const { return n; }

private:
    int n;
};
class Counter
{
public:
    Counter() { n = 0; }

    void increment() { QMutexLocker locker(&mutex); ++n; }
    void decrement() { QMutexLocker locker(&mutex); --n; }
    int value() const { QMutexLocker locker(&mutex); return n; }

private:
    mutable QMutex mutex;
    int n;
};

Qt Concurrent and futures

it is similar to std::async (function)

QFuture<void> future = QtConcurrent::run(aFunction);

This will run aFunction in a separate thread obtained from the default QThreadPool. You can use the QFuture and QFutureWatcher classes to monitor the status of the function.
To use a dedicated thread pool, you can pass the QThreadPool as the first argument:

extern void aFunction();
QThreadPool pool;
QFuture<void> future = QtConcurrent::run(&pool, aFunction);

Passing arguments to the function is done by adding them to the QtConcurrent::run() call immediately after the function name. For example:

extern void aFunctionWithArguments(int arg1, double arg2, const QString &string);

int integer = ...;
double floatingPoint = ...;
QString string = ...;

QFuture<void> future = QtConcurrent::run(aFunctionWithArguments, integer, floatingPoint, string);

Any return value from the function is available via QFuture:

extern QString functionReturningAString();
QFuture<QString> future = QtConcurrent::run(functionReturningAString);
...
QString result = future.result();
extern QString someFunction(const QByteArray &input);

QByteArray bytearray = ...;

QFuture<QString> future = QtConcurrent::run(someFunction, bytearray);
...
QString result = future.result();

Note that the QFuture::result() function blocks and waits for the result to become available. Use QFutureWatcher to get notification when the function has finished execution and the result is available.

// call 'QList<QByteArray>  QByteArray::split(char sep) const' in a separate thread
QByteArray bytearray = "hello world";
QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');
...
QList<QByteArray> result = future.result();

call member function

// call 'void QImage::invertPixels(InvertMode mode)' in a separate thread
QImage image = ...;
QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba);
...
future.waitForFinished();
// At this point, the pixels in 'image' have been inverted
QFuture<void> future = QtConcurrent::run([=]() {
    // Code in this block will run in another thread
});

Concurrent Map

QtConcurrent::mapped() takes an input sequence and a map function. This map function is then called for each item in the sequence, and a new sequence containing the return values from the map function is returned.

QImage scaled(const QImage &image)
{
    return image.scaled(100, 100);
}

QList<QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images, scaled);

The results of the map are made available through QFuture. See the QFuture and QFutureWatcher documentation for more information on how to use QFuture in your applications.

If you want to modify a sequence in-place, use QtConcurrent::map(). The map function must then be of the form:

void scale(QImage &image)
{
    image = image.scaled(100, 100);
}

QList<QImage> images = ...;
QFuture<void> future = QtConcurrent::map(images, scale);
void addToCollage(QImage &collage, const QImage &thumbnail)
{
    QPainter p(&collage);
    static QPoint offset = QPoint(0, 0);
    p.drawImage(offset, thumbnail);
    offset += ...;
}

QList<QImage> images = ...;
QFuture<QImage> collage = QtConcurrent::mappedReduced(images, scaled, addToCollage);

The reduce function will be called once for each result returned by the map function, and should merge the intermediate into the result variable. QtConcurrent::mappedReduced() guarantees that only one thread will call reduce at a time, so using a mutex to lock the result variable is not necessary. The QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done. If QtConcurrent::UnorderedReduce is used (the default), the order is undefined, while QtConcurrent::OrderedReduce ensures that the reduction is done in the order of the original sequence.

Blocking Variants :Each of the above functions has a blocking variant that returns the final result instead of a QFuture. You use them in the same way as the asynchronous variants.

QList<QImage> images = ...;

// Each call blocks until the entire operation is finished.
QList<QImage> future = QtConcurrent::blockingMapped(images, scaled);

QtConcurrent::blockingMap(images, scale);

QImage collage = QtConcurrent::blockingMappedReduced(images, scaled, addToCollage);

very useful links
QFuture QFutureWatcher

JSON With Qt

QJsonDocument
The QJsonDocument class provides a way to read and write JSON documents.
isArray,isObject,isNull,isEmpty to check the main content of document
object(),array() to get main QJsonObject or QJsonArray
toJson() convert it to QByteArray (json string)
QJsonObject
A JSON object is a list of key value pairs, where the keys are unique strings and the values are represented by a QJsonValue.
A QJsonObject can be converted to and from a QVariantMap. You can query the number of (key, value) pairs with size(), insert(), and remove() entries from it and iterate over its content using the standard C++ iterator pattern.
QJsonArray
A JSON array is a list of values. The list can be manipulated by inserting and removing QJsonValue‘s from the array.
A QJsonArray can be converted to and from a QVariantList. You can query the number of entries with size(), insert(), and removeAt() entries from it and iterate over its content using the standard C++ iterator pattern.
QJsonValue
A value in JSON can be one of 6 basic types:
JSON is a format to store structured data. It has 6 basic data types:bool QJsonValue::Bool
double QJsonValue::Double
string QJsonValue::String
array QJsonValue::Array
object QJsonValue::Object
null QJsonValue::Null
A value can represent any of the above data types. In addition, QJsonValue has one special flag to represent undefined values. This can be queried with isUndefined().
The type of the value can be queried with type() or accessors like isBool(), isString(), and so on. Likewise, the value can be converted to the type stored in it using the toBool(), toString() and so on.
Values are strictly typed internally and contrary to QVariant will not attempt to do any implicit type conversions. This implies that converting to a type that is not stored in the value will return a default constructed return value.
you can use fromVariant(const QVariant &variant) to QJsonValue from QVariant

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}
QFile file("json.txt");
file.open(QFile::ReadOnly);
QByteArray data=file.readAll();
QJsonObject mainObject=QJsonDocument::fromJson(data).object();
qDebug()<<"first name : "<<(*mainObject.find("firstName")).toString();
qDebug()<<"address  : "<<mainObject["address"].toObject()["streetAddress"].toString();
qDebug()<<"phone number  : "<<mainObject["phoneNumbers"].toArray()[0].toObject()["number"].toString();
first name :  "John"
address  :  "21 2nd Street"
phone number  :  "212 555-1234"