Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Home
Help
Recent changes
Contributor Help Pages
Tasks and Tools
Modify a page
Add new content
Page elements
Typographical guidelines
More markup help
Translator Help Pages
Get a Translator Account
Languages represented
Translation Workflow
Translate a Page
Off-line Translation
Translation Statistics
More Help pages
Search
Search
English
Log in
Personal tools
Log in
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Special pages
Printable version
Settings
Group
Category:Phonon
Contribute/List of KDE Modules
Development
Development/FAQs/General FAQ
Development/FAQs/Technical FAQ
Development/KDevelop-PG-Qt Introduction
Development/Tools
Development/Tutorials
Development/Tutorials/CommandLineArguments
Development/Tutorials/Common Programming Mistakes
Development/Tutorials/First program
Development/Tutorials/First program/KDE4
Development/Tutorials/First program/KF5
Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for Beginners
Development/Tutorials/Metadata/Nepomuk/TipsAndTricks
Development/Tutorials/Physical Simulation
Development/Tutorials/Qt4 Ruby Tutorial
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3
Development/Tutorials/Saving and loading
Development/Tutorials/Setting Up
Development/Tutorials/Using Actions
Development/Tutorials/Using KXmlGuiWindow
Documentation Primer
Edit Markup
Getting Started
Help:Contents
Help:Contribute
How To Convert a UserBase Manual to Docbook
KDE Frameworks
KDE Frameworks/Getting Started
KDE TechBase:About
KDE TechBase:Contributors
KDE TechBase:General disclaimer
KDE TechBase:Privacy policy
Off-line Translation
Projects/Calligra/Plugin Tutorials
Toolbox
Translate a Page
Translation Workflow
Typographical Guidelines
User:Neverendingo
Welcome to KDE TechBase
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cpx - Pu-Xian Min
cpx-hans - Pu-Xian Min (Simplified Han script)
cpx-hant - Pu-Xian Min (Traditional Han script)
cpx-latn - Pu-Xian Min (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Crimean Tatar (Romania)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Dagaare
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hno - Northern Hindko
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang Chinese
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kʋsaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nyn - Nyankole
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Tayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wo - Wolof
wuu - Wu Chinese
wuu-hans - Wu Chinese (Simplified)
wuu-hant - Wu Chinese (Traditional)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yue - Cantonese
yue-hans - Cantonese (Simplified)
yue-hant - Cantonese (Traditional)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
<languages /> {{Review|Port to KF5 and KDevelop5}} ==Introduction== Often in engineering you want to animate things, and KDE has a great method for doing this. I found''' KDevelop''' particular helpful due to the auto-completion. However, this tutorial also gives you the vi/emacs/randomEditor version. Since the code will become relatively long for a tutorial, the tutorial is split into sections. At the end of each section, the program will produce something. In this tutorial you will learn how to: * get two or more widgets in one window * plot data in an xy-plot * draw something on a widget * animate something engineering / physics based. What is easier than a bouncing ball * use KDevelop if you choose to so (the inside help system and link to the KDE and QT help are great) [[image:introtokdetutorialBouncingBall.png|400px|center]] ==Setup== ;In '''KDevelop:''' :<menuchoice>Project->New from Template -> Qt4 CMake Gui application with name "FallingBall" -> Next -> Finish.</menuchoice> Open CMakeLists.txt by double clicking on it. ;In a Text Editor: :Make directory and create a <tt>CMakeLists.txt</tt> file, which cmake requires to find dependencies and compile the program. <syntaxhighlight lang="cmake"> project (FallingBall) find_package(KDE4 REQUIRED) include_directories(${KDE4_INCLUDES}) set(FallingBall_SRCS main.cpp FallingBall.cpp ) kde4_add_executable(FallingBall ${FallingBall_SRCS}) target_link_libraries(FallingBall ${KDE4_KDEUI_LIBS}) </syntaxhighlight> The first line gives a name to the project, and the second ensures that the klibs are installed; while the third sets the header files appropriately. The "set" line is the most important. We have to put in all the ".cpp" files that we use in here. For now, just add the main.cpp and the FallingBall.cpp. Others will join later. Finally, define the executable and link all files. ==Basic structure== Now lets start with main.cpp: This is just the starter point of the application, which starts the main window. Include conventional headers, which allow to create a KDE application, a nice AboutBox and handle command line arguments. <syntaxhighlight lang="cpp-qt"> #include <KApplication> #include <KAboutData> #include <KCmdLineArgs> //Include the header of the new main window. #include "FallingBall.h" int main (int argc, char *argv[]) { KAboutData aboutData( "FallingBall", 0, ki18n("FallingBall"), "1.0", ki18n("This is some random text"), KAboutData::License_GPL, ki18n("Copyright (c) 2012 Your name") ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app; FallingBall* mainWindow = new FallingBall(); mainWindow->show(); return app.exec(); } </syntaxhighlight> The header files should be self-explanatory. Of special interest is the second part. We create a new application by the name of "app". Then we create a new main window from the type FallingBall. The central things will happen in this class, hence mainWindow. After creation, we show the mainWindow and execute the app, which waits for user interactions, does the repainting, ... Now lets come to FallingBall.h. The header for the main program. <syntaxhighlight lang="cpp-qt"> #ifndef FallingBall_H #define FallingBall_H #include <KXmlGuiWindow> #include <QTimer> #include <KPlotWidget> class FallingBall : public KXmlGuiWindow { public: FallingBall(QWidget *parent=0); private: QWidget *master; KPlotWidget *xyPlot; }; #endif // FallingBall_H </syntaxhighlight> This file will be expanded later on. Lets keep it simple for now, such that we can test the current version and are not bugged down in many interrelated bugs. The KXmlGuiWindow allows us fancy application. The Qtimer is required for the motion of the ball and the KPlotWidget shows us the graph of the data. This main window is a child of the KXmlGuiWindow. and has a constructor with a default value of 0, which implies it is the main window. We also add one QWidget, which will allow us to position multiple things on the main window. Also we add already the KPlotWidget, since this widget is debugged and working nicely. Now lets come to the main window: FallingBall.cpp: <syntaxhighlight lang="cpp-qt"> #include "FallingBall.h" #include <QHBoxLayout> FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) { master = new QWidget(); xyPlot = new KPlotWidget(); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(xyPlot); master->setLayout(layout); setCentralWidget(master); setupGUI(); QTimer *timer = new QTimer(this); timer->start(100); } </syntaxhighlight> We include the appropriate header and the QHBoxLayout, which allows us to place multiple widgets in the main window. We create a new master QWidget, which will hold the picture of the falling ball and the graph. Then, we create an instance of the KPlotWidget. We define a new layout to place the things on the master. Here we choose horizontal layout but vertical and grid layout exist. Which can be further divided. Therefore, almost endless possibilities. We add the xyPlot widget to the layout for now. With only one well tested widget, we can test our code. Next we assign the layout to the master widget. We can only assign layouts to widgets, even empty once. This main window is not a QWidget, hence we cannot assign a layout to it. After the master is setup, we can tell the compiler that this master should be the central widget and setup the GUI, which does some administrative stuff. Finally, we define a new timer which will support the animation and we set the refresh rate to 100 milliseconds. Now we should be able to start the application. Now lets test this minimal program: ;In KDevelop: *Compile with F8 *setup the execution by Run->Configure Launches. Click on the Name "Falling Ball" and add "+" a launch to it. *configure the launch by clicking on the Project Target: FallingBall/FallingBall *and OK. From now on you can just hit ... (If you have multiple open projects, you must switch between different launches by choosing the project under "Run-Current Launch Configuration) *F9 ;In Editor: <code>cmake . && make && ./FallingBall</code> ==Adding physics== Now lets create the ball logic, which calculates the position,... . No drawing is done here, that will be done in the ball widget later. Always remember, use small (but meaningful) building blocks. That way you can test them and find problems fast. ;BallLogic.h <syntaxhighlight lang="cpp-qt"> #ifndef _BALL_LOGIC_H_ #define _BALL_LOGIC_H_ #include <QWidget> class BallLogic : public QWidget { Q_OBJECT public: BallLogic(double dTime=0.1); double getPosition(); double getTime(); private: double position; double velocity; double acceleration; double time,dTime; public slots: void nextTimeStep(); }; #endif </syntaxhighlight> This might seem strange: if we just want to put the logic in here, no drawing, why would we need a QWidget? Answer, the logic includes the next time step, which is a so called slot. We discuss the slots later. Only this much here. Since we want to have a "slot" we require to inherit from QWidget, which has slots. This slot must be public, i.e. we want to access it from outside this class. The Q_OBJECT is a macro, which will setup some default things. The constructor requires a time step in seconds while the getPosition returns the current position. The private variables are self explanatory. Now lets go into the ball logic code BallLogic.cpp: <syntaxhighlight lang="cpp-qt"> #include "BallLogic.h" BallLogic::BallLogic(double dTime) { this->dTime = dTime; acceleration = -9.81; velocity = 0; position = 590; time=0; } double BallLogic::getPosition() { return position; } double BallLogic::getTime() { return time; } void BallLogic::nextTimeStep() { time += dTime; if(position<=0 && velocity<0) velocity=-velocity; velocity += acceleration*dTime; position += velocity*dTime+0.5*acceleration*dTime*dTime; } </syntaxhighlight> The constructor sets the time step of this class and defines the acceleration constant, together with some starting conditions: we start at pixel, with zero velocity at time zero. The getPosition method returns the current position and the next time step does the calculation. If the current position and velocity are negative, the ball is hitting the floor and has to bounce back. (Omitting the velocity condition might result in a strange behavior.) Bouncing back implies a reversal of the velocity. The new velocity and position are calculated according to Newtonian mechanics. Check the corresponding Wikipedia if you like. Now lets test it again. Frequent testing is the path to success. First add the new BallLogic.cpp to the CMakeLists.txt! Then, if you use KDevelop "F8" and "F9". Else use make and execute the application. ==Adding drawing functions== After the logic is done, now it is time to do the drawing. First the header file. <syntaxhighlight lang="cpp-qt"> #ifndef _BALL_GRAPH_H_ #define _BALL_GRAPH_H_ #include <QWidget> #include <KPlotWidget> #include <KPlotObject> #include <KPlotAxis> #include <QtGui> #include "BallLogic.h" class BallGraph : public QWidget { Q_OBJECT public: BallGraph(BallLogic *logic, KPlotWidget *xyPlot, QWidget *parent = 0); QSize minimumSizeHint() const; QSize sizeHint() const; protected: BallLogic *logic; KPlotWidget *xyPlot; KPlotObject *xyData; void paintEvent(QPaintEvent *event); double radius; public slots: void nextAnimationFrame(); }; #endif </syntaxhighlight> Our ball drawing widget will inherit from QWidget, which is an feasible background. As such it requires again the Q_OBJECT macro, see before. Now we come to a small detail. Our drawing widget needs to have a pointer to the xy-plot widget such that it can post data there. Moreover, the drawing widget requires a pointer to the ball logic, such that it can inquire about the position of the ball at the current time. All three widgets need to talk to each other, therefore a pointer is required which allows for communication, xyPlot. To allow for usage of the xy-plot (KPlotWidget) three header files are included. The second defines the data structure, which can be plotted. This data structure is again a pointer called xyData. The radius defines the radius of the ball, and paintEvent and nextAnimationFrame allow for drawing of the next time frame. The paintEvent, which does the drawing, is called whenever the update() method is called. The nextAnimationFrame only calls all the update methods. (The update method is inherited from QWidget). minimumSizeHint and sizeHint specify the minimum and suggested size of this widget. Remember, this widget is only the drawing widget on the right hand side. They could be different, but lazy people as me set them equal. Now, on to the BallGraph.cpp <syntaxhighlight lang="cpp-qt"> #include "BallGraph.h" BallGraph::BallGraph(BallLogic* logic, KPlotWidget* xyPlot, QWidget* parent): QWidget(parent) { this->logic = logic; radius = 20; setBackgroundRole(QPalette::Base); //Background color: this nice gradient of gray setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //allow for expanding of the widget, aka use the minimumSizeHint and sizeHint // For xy plot using KplotWidget this->xyPlot = xyPlot; //set pointer xyPlot->setMinimumSize( 600, 600 ); //set minimum size in pixel xyData = new KPlotObject( Qt::red, KPlotObject::Lines, 2 ); //the data lines are drawn in red with thickness 2 xyPlot->setLimits(0, 100, 0, 600); //the data limits are 0 to 100 in the x-direction and 0 to 600 in the y-direction (initially we start at point 590) xyPlot->addPlotObject(xyData); //assign the data pointer to the graph. From now on, if the data pointer contains data, it is plotted in the graph xyPlot->setBackgroundColor( QColor(240, 240, 240) ); //background: light shade of gray xyPlot->setForegroundColor( Qt::black ); //foreground: black xyPlot->axis( KPlotWidget::BottomAxis )->setLabel("Time [s]"); //set x-axis labeling xyPlot->axis( KPlotWidget::LeftAxis )->setLabel("Position [m]"); //set y-axis labeling } QSize BallGraph::minimumSizeHint() const { return QSize(200, 600); } QSize BallGraph::sizeHint() const { return QSize(200, 600); } void BallGraph::nextAnimationFrame() { double time=logic->getTime(); double position=logic->getPosition(); xyData->addPoint(time, position); xyPlot->update(); update(); } void BallGraph::paintEvent(QPaintEvent* event) { double position=logic->getPosition(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); //draw ball painter.setPen(QPen(Qt::red, 4)); painter.drawEllipse(95, 575-position, 2*radius, -2*radius); //draw floor painter.fillRect( 10, 595, 180, -20 , QColor(40, 40, 40) ); } </syntaxhighlight> The constructor connects the pointers of the ball logic and the KplotWidget to the current class and sets the radius. The remainder of the constructor is explained with the comments. The minimumSizeHint and sizeHint were discussed before. During each animation time step, the current physical time and ball position is queried from the ball logic class. This data is added to the data stream, which will be plotted in the xy-Plot using KPlotWidget. The pointer is used to call the update method. Finally, the update, aka drawing, method of this class is called. During the drawing in paint event, first the current position of the ball in inquired using the pointer. Then we use a painter, to draw on this ball drawing widget. Clearly, everybody wants to use Antialiasing. Then we draw the ball using a red color and a 4 pixel wide pen. We draw an ellipse with the given boundary box. First the bottom left coordinate of the bounding rectangle is given. Be aware, the computer screens have the zero position at the top left corner, not as most people would expect at the bottom left corner. Therefore, we need to calculate the y-positions by some negative signs. The total window height is 600, drawing the floor requires 25, therefore, 575-position gives the bottom coordinate. The ball has twice the radius diameter. Since the y-coordinates count from the top side, we have to use a minus again. Finally we draw the floor in dark gray with a filled rectangle of given dimensions: 180 wide and 20 pixel high while the bottom left corner has the given coordinates. ==Assembling== Now we need to wire everything together in FallingBall.cpp and FallingBall.h First lets do the header file, which should look like this now: <syntaxhighlight lang="cpp-qt"> #ifndef FallingBall_H #define FallingBall_H #include <KXmlGuiWindow> #include <QTimer> #include <KPlotWidget> #include "BallGraph.h" #include "BallLogic.h" class FallingBall : public KXmlGuiWindow { public: FallingBall(QWidget *parent=0); private: QWidget *master; BallLogic *logic; KPlotWidget *xyPlot; BallGraph *ballGraph; }; #endif // FallingBall_H </syntaxhighlight> We include the header files for the logic and the graph and add two pointers for the two widgets in the private section. Now to the wiring in the FallingBall.cpp: <syntaxhighlight lang="cpp-qt"> #include "FallingBall.h" #include <QHBoxLayout> FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) { master = new QWidget(); xyPlot = new KPlotWidget(); logic = new BallLogic(); ballGraph = new BallGraph(logic, xyPlot); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(ballGraph); layout->addWidget(xyPlot); master->setLayout(layout); setCentralWidget(master); setupGUI(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), logic, SLOT( nextTimeStep() ) ); connect(timer, SIGNAL(timeout()), ballGraph, SLOT(nextAnimationFrame())); timer->start(100); } </syntaxhighlight> Mostly, it is the same as before, now we only define the pointers for the xy-plot and the ball-logic and give those pointers to the constructor of the ball-drawing widget. We add the drawing widget to the layout. The widgets are added from the left to the right: the first goes left, the second goes to the right of that and so on. Finally, we start the animation with some connect action. First we connect the signal / event of the timer reaching the timeout (after 100ms), to the logic -> next time step. I envision this as a signal comes from a source (timer) and reaches a destination (ball logic) at a given slot. This event triggers the nextTimeStep method defined in the BallLogic class. Similarly whenever the 100ms are passed, the ballGraph gets a signal to add a new data point to the xy-Data and draw it using the update method of KPlotWidget and then update itself, draw the new ball and floor. With the updated CMakeLists.txt: we are done. <syntaxhighlight lang="cmake"> set(FallingBall_SRCS main.cpp FallingBall.cpp BallLogic.cpp BallGraph.cpp ) </syntaxhighlight> If you made no mistake, you should get a application that looks similar to the one on the top. ==Extensions== {{Tip|2=Challenge 1|1=Extend the program by plotting the velocity in the xy-graph along with the position.}} {{Info|2=Challenge 2|1=If you look at the graph it becomes obvious that the bouncing is damped. Why? Where would you have to change things, to remove the damping? One "else" is sufficient.}} [[Category:Programming]] [[Category:Tutorial]]
Toggle limited content width