QT5 Official Demo analysis set 36--wiggly Example

Source: Internet
Author: User
Tags drawtext

All articles in this series can be viewed here http://blog.csdn.net/cloud_castle/article/category/2123873

Next QT5 official demo set 35--music Player


Today also brings an interesting small example, as shown in the text that we enter will be displayed in the central window and float in a sine wave shape.

This example involves the Qbasictimer class in the Qt timer family and the very useful qfontmetrics class.



When we deploy the app on a mobile device, Qt adds "-small-screen" command-line arguments to the app. Therefore, by judging whether the parameter exists, We can choose a different display mode for the application, as shown in the main () function in the demo:

#include <QApplication> #include "dialog.h" int main (int argc, char *argv[]) {    qapplication app (argc, argv);    BOOL SmallScreen = Qapplication::arguments (). Contains ("-small-screen");    Dialog Dialog (0, smallscreen);    if (!smallscreen)         //If not smallscreen direct display, otherwise full-screen display        dialog.show ();    else        Dialog.showfullscreen ();    return app.exec ();}

The Dialog class inherits from Qdialog, uses a vertical layout to add a central window and an input box, and connects the textChanged (QString) signal of the input box to the SetText (QString) slot function of the center window.


Then take a look at our wigglywidget.h:

#include <QBasicTimer> #include <qwidget>//! [0]class wigglywidget:public qwidget{    q_objectpublic:    wigglywidget (Qwidget *parent = 0);p ublic slots:    void SetText (const QString &newtext) {text = NewText;}//When the text transformation in the input box is performed, the slot function is executed because the window is refreshed every 60 milliseconds, so there is no need to call Update () protected:< C3/>void paintevent (qpaintevent *event);    void TimerEvent (qtimerevent *event);p rivate:    qbasictimer timer;    QString text;    int step;};
The Qbasictimer is a fast, lightweight timer class that is suitable for use in environments with high performance requirements such as embedded systems.

It does not inherit from the qobject like Qtimer, so it does not have the ability to use a signal slot,

But we can use it to repeatedly send Qtimerevent events for Qobject and its derived class objects, by overloading TimerEvent (qtimerevent*) to capture the event.


Wigglywidget.cpp:

#include <QtWidgets> #include "wigglywidget.h"//! [0]  Wigglywidget::wigglywidget (Qwidget *parent): Qwidget (parent) {setbackgroundrole (qpalette::midlight);   Set the background color to bright white setautofillbackground (true);        Remember to set this property to True qfont NewFont = font ();    Then get the Font object for the window Newfont.setpointsize (newfont.pointsize () + 20);    Increase the number of SetFont (NewFont) 20th;    Step = 0;        Timer.start (, this); Turn on the timer, 60 milliseconds apart}//! [0]//! [1]void wigglywidget::p aintevent (qpaintevent */* Event */)//! [1]//! [2] {static const int SINETABLE[16] = {//sine-wave y-Value sampling array 0, 38, 71, 92, 100, 92, 71, 38, 0,-38,-71,-92, 1    00,-92,-71,-38};           Qfontmetrics Metrics (font ());      Initializes the font with the current form qfontmetrics int x = (width ()-metrics.width (text))/2;  Get information about the displayed text by metrics, and center the text in int y = (height () + metrics.ascent ()-metrics.descent ())/2; As for ascent and descent, we explain Qcolor color;//! below. [2]//! [3] qpainter painter (this);//! [3]//! [4] for (int i = 0; i < Text.size ();        ++i) {//Gets the number of characters in text and loops int index = (step + i)% 16; COLOR.SETHSV ((15-index) * 16, 255, 191);        Using HSV to set the color value for each character, the three parameters represent hue, saturation, luminance painter.setpen (color), respectively;                         Painter.drawtext (x, Y-((Sinetable[index] * metrics.height ())/400),//400 to control the amplitude of the sine wave, the larger the value fluctuation the smaller        QString (Text[i]));         x + = Metrics.width (Text[i]); Increases the value of x by the current character width}}//! [4]//! [5]void wigglywidget::timerevent (qtimerevent *event)//! [5]//! [6]                                          {if (Event->timerid () = = Timer.timerid ()) {//We use Timerid to determine if this timerevent is triggered by our defined timer ++step;                     Update ();    Refresh Display} else {qwidget::timerevent (event); If not, continue with the event}//! [6]}


We must remember when we use QT to draw graphics, like drawrect () or something, we enter the position of the coordinates is the image of the upper left corner of the location, simply refers to where to play where ~

But when it comes to using DrawText (), it doesn't seem like it. It seems that the origin of the text has become the lower left corner, but still feel almost the meaning? If you have some doubts about this, take a look at the following picture, yes, the origin of the figure is our true origin of the text. It is the intersection of baseline and the left side of the text.



With this picture, ascent and descent are obvious, respectively, the distance between the top and bottom of the text and the baseline.

int y = (height () + metrics.ascent ()-metrics.descent ())/2;

Then this line of code is obvious, and it is the y-coordinate of the baseline on the window when we are centering the text vertically.

If you convert this equation to this, it might be more obvious:

int y = metrics.ascent () + (height ()-metrics.ascent ()-metrics.descent ())/2;


Maybe we use qfontmetrics to use some of its handy functions such as height (),

In fact, height () is equal to Ascent () +descent () +1, and the last 1 is the width of the baseline.


Well, with the beating character, let's Get here first O (∩_∩) o~


QT5 Official Demo analysis set 36--wiggly Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.