QT Learning Notes (v) Qgraphicspixmapitem and Qgraphicsscene Programming instance icons drag the gradient effect

Source: Internet
Author: User

At the request of everyone, or to put the complete project file, we save something: http://www.kuaipan.cn/file/id_48923272389086450.htm

First look at the implementation of the effect, I use the group of 7-inch screen, the host is mini2440, the resolution is 800*480, the program is relatively rough, but the beginning of learning people still have a little revelation, we progress together.

Qgphicsview,qgraphicsscene,qgraphicsitem,qgraphicspixmapitem is a subclass of Qgraphicsitem in Qt.

Distinguish between instances where they are created: View,scene,item, and then through their respective methods Scene->additem (item), View->setscene (scene), can achieve a similar effect, want to further customize, then inherit Qgraphicsitem or qgraphicspixmapitem, then rewrite the methods of Paint (), boundingrect (), and suppose you want to get mouse events, rewrite mousepressevent, and so on. Note that once the Mousepressevent method is rewritten, it is assumed that QT will no longer take the initiative to handle item regardless of the press event, and can add Qgraphicsitem to your rewritten Mousepressevent method: Mousepressevent (event); Solve the problem, that is, you get the mouse event, but still let QT handle this mouse event.

The item in the program can be dragged horizontally, the same time the icon size will be gradient, the middle of the largest, both sides gradually smaller.

Figure 1


Figure 2


Figure 3



The following is the source program folder structure:


Mainwindow.h and Main.cpp are QT self-generated code, I didn't produce the form UI

Myscene.h with a scene.cpp is defined class Myscene, inherited from Qgraphicsscene, my purpose is to get its mouse events

Nodeui.h and nodeui.cpp are defined classes Nodeui, inherit from Qgraphicspixmapitem, the purpose is quite many.

The following detailed source files: myscene.h and myscene.cpp are relatively simple and implement a function

Myscene.h

#ifndef myscene_h#define myscene_h#include <qgraphicsscene>class myscene:public qgraphicsscene{q_objectpublic :    Explicit MyScene (Qobject *parent = 0);p rivate:    void Mousemoveevent (Qgraphicsscenemouseevent *event);    void Mousepressevent (Qgraphicsscenemouseevent *event);    void Mousereleaseevent (Qgraphicsscenemouseevent *event); signals:    void ismoving (qpointf &pos);p ublic Slots: Private:    qpointf  beforepos;    qpointf  Releasepos;}; #endif//Myscene_h

Myscene.cpp

#include "myscene.h" #include <QGraphicsSceneMouseEvent> #include <QPointF> #include <QDebug> Myscene::myscene (Qobject *parent):    qgraphicsscene (parent) {}void myscene::mousemoveevent ( Qgraphicsscenemouseevent *event) {    //qpointf pos = Event->scenepos ();    qpointf POS (Event->scenepos (). x ()-beforepos.x (), Event->scenepos (). Y ()-beforepos.y ());    Emit ismoving (POS);    Qdebug () << "x:" <<pos.x () << "y:" <<pos.y ();} void Myscene::mousepressevent (Qgraphicsscenemouseevent *event) {    Beforepos = Event->scenepos ();} void Myscene::mousereleaseevent (Qgraphicsscenemouseevent *event) {    Releasepos = Event->scenepos ();}

Again see NODEUI.H and Nodeui.cpp, on the original qgraphicspixmapitem on the basis and if the point of their own things

#ifndef nodeui_h#define nodeui_h#include <QGraphicsPixmapItem> #include <QGraphicsItem> #include < qstyleoptiongraphicsitem> #include <QPainter> #include <QGraphicsSceneMouseEvent> #include < Qpointf>class nodeui:public qobject,public qgraphicspixmapitem{    q_objectpublic:    NodeUI ();    Nodeui (QString &file,qstring &text,int imagesize=80);    Setup function    void Setmypixmap (QString &file,int size);    void Setmytext (QString &text);    QString Getmytext ();    virtual function    QRECTF boundingrect () const;    Qpainterpath shape () const;signals:    void nodeismoving (qpointf &pos);    void nodeispressed ();p rotected:    void Mousepressevent (Qgraphicsscenemouseevent *event);    void Mousereleaseevent (qgraphicsscenemouseevent *event);p rivate:    //qstring myimage;    QString MyText;}; #endif//Nodeui_h

Nideui.cpp

#include "nodeui.h" #include <QPixmap> #include <iostream> #include <qdebug>nodeui::nodeui () {}/* Note:imagesize = in the Nodeui.h*/nodeui::nodeui (QString &file,qstring &text,int imagesize) {Setmytext (t    EXT); Setmypixmap (file,imagesize);} void Nodeui::setmytext (QString &text) {myText = text;}    void Nodeui::setmypixmap (QString &file,int size) {//myimage = file;    Qpixmap Pixmap;    Pixmap.load (file);    Pixmap= pixmap.scaled (Size,size,qt::ignoreaspectratio, qt::smoothtransformation); Setpixmap (pixmap);}    QRECTF nodeui::boundingrect () const{qrect rect = This->pixmap (). Rect ();    Return QRECTF (rect); Return QRECTF (0,0,rect.width (), Rect.width () +15);} void Nodeui::p aint (qpainter *painter, const qstyleoptiongraphicsitem *option, Qwidget *widget) {Qpixmap Pixma    p = This->pixmap ();    Qrect rect = Pixmap.rect ();    Painter->drawpixmap (RECT,PIXMAP); Print Name,calculate The text ' s Heigh & width for center layout    Qpen Pen (qt::black);    Painter->setpen (pen);    Painter->setrenderhint (qpainter::antialiasing);    Qfont font ("Verdana", 8, Qfont::normal);    Painter->setfont (font);    Painter->drawtext (QRECTF (0,rect.height (), Rect.width (), qt::aligncenter,mytext);        if (Option->state & Qstyle::state_sunken) {QRECTF rect1 = Boundingrect ();        Qpen Pen (Qt::d arkgreen);    Painter->setpen (Qpen (Qt::d arkgreen));    }else {}}qpainterpath nodeui::shape () const{QRECTF rect = Boundingrect ();    Qpainterpath path;    Path.addroundrect (rect, 5,5); return path;}    void Nodeui::mousepressevent (Qgraphicsscenemouseevent *event) {emit nodeispressed ();    Qdebug () << "pressed"; Qgraphicsitem::mousepressevent (event);}    void Nodeui::mousereleaseevent (Qgraphicsscenemouseevent *event) {update (Boundingrect ()); Qgraphicsitem::mousereleaseevent (event);} QString Nodeui::getmytext () {return myText;}

Finally, the scene and item file Mainwindow.cpp, inherited the Qmainwindow, the role is to draw an application framework

Mainwindow.h

#ifndef mainwindow_h#define mainwindow_h#include <QtGui/QMainWindow> #include <QGraphicsView> #include <QGraphicsScene> #include <QPointF> #include "nodeui.h" #include "myscene.h" #include <qmap>class    Mainwindow:public qmainwindow{Q_objectpublic:mainwindow (qwidget *parent = 0);    ~mainwindow ();    Nodeui *selectednodeui ();    BOOL Isnodeuiclicked ();    void Nodeuisizeadjust ();    Varprotected:private:void Getscreeninfo ();    Qgraphicsview *view;    Qgraphicsscene *scene;    MyScene *scene; Instead of (Nodeui *nodeui;) & (qpointf nodeuipos;)//Now deprecated, because qmap order cannot be artificially set, according to internal key self-active ascending//qmap<nodeui*,qpoin    tf>nodeuimaps;    Nodeui *currentnodeui;    Nodeui pressed or released volatile bool mpressed;    Qlist<nodeui*> nodeuilists;    Qlist<qpointf> nodeuiposlists;        qlist<qpixmap> nodeuipixmaplists;/* struct {qlist<nodeui*> nodelists;    Qlist<qpointf> poslists;    }SS; *///deprecated    Nodeui *nodeui;    qpointf Nodeuipos;    Sceen size info;    Qint16 Sceensizex;    Qint16 sceensizey;private slots:void ismoving (qpointf &pos);    void IsPressed ();    void isreleased (); void SelectionChanged (); signals:void nodeuiclicked (nodeui* node);}; #endif//Mainwindow_h
Mainwindow.cpp

#include "mainwindow.h" #include <QDesktopWidget> #include <QApplication> #include <qpixmap># Include <QGraphicsItem> #include <QMouseEvent> #include <QWidget> #include <qgraphicspixmapitem > #include <QMessageBox> #include <qdebug>const qreal my_nodeui_pos_y = 200;const qreal My_nodeui_dis = 110  ; Const Qreal My_nodeui_sta = 90;const int mynodeui_size = 100;const int mynodeui_size_m = 20;const int screen_size = 800;    Mainwindow::mainwindow (Qwidget *parent): Qmainwindow (parent) {//Initialize mpressed = false;    Get Windows size getscreeninfo ();    view = new Qgraphicsview;    Scene = new MyScene ();    Scene->setscenerect (0,0,800,480);    New QString file;    QString text;    qpointf POS;    nodeui* node;    home:1 file = QString (":/images/home.png");    Text = QString ("Home");    pos = qpointf (my_nodeui_sta,my_nodeui_pos_y);    node = new Nodeui (file,text,mynodeui_size);    Node->setpos (POS); Nodeuilists.append (nODE);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    /* Here cannot delete node!!!!!!!!!!!!!!!    Delete node;    *///vidio:2 File = QString (":/images/securitycamera.png");    Text = QString ("Vidio");    pos = qpointf (my_nodeui_sta+my_nodeui_dis*1,my_nodeui_pos_y);    node = new Nodeui (file,text,mynodeui_size);    Node->setpos (POS);    Nodeuilists.append (node);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    Application:3 file = QString (":/images/application.png");    Text = QString ("Application");    pos = qpointf (my_nodeui_sta+my_nodeui_dis*2,my_nodeui_pos_y);    node = new Nodeui (file,text,mynodeui_size);    Node->setpos (POS);    Nodeuilists.append (node);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    Network:4 file = QString (":/images/network-2.png");    Text = QString ("Network");    pos = qpointf (my_nodeui_sta+my_nodeui_dis*3,my_nodeui_pos_y); node = New Nodeui (file,text,mynodeui_size);    Node->setpos (POS);    Nodeuilists.append (node);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    Computer:5 file = QString (":/images/smartphone.png");    Text = QString ("Phone");    pos = qpointf (my_nodeui_sta+my_nodeui_dis*4,my_nodeui_pos_y);    node = new Nodeui (file,text,mynodeui_size);    Node->setpos (POS);    Nodeuilists.append (node);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    Customize:5 file = QString (":/images/customize.png");    Text = QString ("Setting");    pos = qpointf (my_nodeui_sta+my_nodeui_dis*5,my_nodeui_pos_y);    node = new Nodeui (file,text,mynodeui_size);    Node->setpos (POS);    Nodeuilists.append (node);    Nodeuiposlists.append (POS);    Nodeuipixmaplists.append (Node->pixmap ());    Another calculation uisize nodeuisizeadjust ();    int i = 0; foreach (nodeui* node_temp,nodeuilists) {node_temp->setflags (QGRAPHICSITEM::ITEMISMOVABLe |        qgraphicsitem::itemisselectable);        Qdebug () << "Name:" <<node_temp->getmytext () <<nodeuiposlists.at (i);        Scene->additem (node_temp);    i++;    }//Stand-alone View->setscene (scene) for button;    Set drag mode//view->setdragmode (Qgraphicsview::rubberbanddrag);    View->setrenderhints (qpainter::antialiasing);    No menu View->setcontextmenupolicy (Qt::nocontextmenu);    View->setbackgroundbrush (Qimage (":/images/shuibo2.jpg"));    View->setviewportupdatemode (qgraphicsview::boundingrectviewportupdate);    View->setcachemode (Qgraphicsview::cachebackground);    Setcentralwidget (view); Setwindowtitle (TR ("Main window"));}    Slot, when scene mouse drag is run//control UI icon horizontal void mainwindow::ismoving (qpointf &pos) {int i=0; if (mpressed) {foreach (nodeui* node,nodeuilists) {Node->setpos (nodeuiposlists.at (i). x () +pos.x (            ), my_nodeui_pos_y);        i++;    } nodeuisizeadjust (); }}//Groove, when Nodeui mouse presses fortuneLine, call the Selectednodeui function, update the CURRENTNODEUI variable//In addition, SelectionChanged () is also a slot, called by scene Void Mainwindow::ispressed () {    SelectionChanged (); mpressed = true;}    Slots, run when Nodeui Mouse is released//should set the flag bit, let UI picture stop response to mouse drag event void mainwindow::isreleased () {mpressed = false;    if (isnodeuiclicked ()) Qdebug () << "clicked"; Qdebug () << "release";}    Slot, when the scene's SelectedItem changes, send the same name signal to this slot void mainwindow::selectionchanged () {int i=0,j=0;    Qlist<qgraphicsitem *> items = Scene->selecteditems ();        if (items.count () = = 1) {//the coordinates of the currently selected UI icon qpointf pos = Items.first ()->pos ();        nodeui* node_temp = Dynamic_cast<nodeui *> (Items.first ());        Qdebug () << "items.x:" <<pos.x () << "Items.y:" <<pos.y ();            foreach (nodeui* node,nodeuilists) {if (node = = node_temp) break;        i++;        } j=i;        i=0; foreach (qpointf ppos,nodeuiposlists) {nodeuiposlists[i].setx ((i-j) *my_nodeuI_dis+pos.x ());            Nodeuiposlists[i].sety (my_nodeui_pos_y);        i++;    }} else {return; }}//infers whether the Nodeui received is a click signal.    It is inferred that the POS of the Nodeui object that is currently clicked is compared to the location stored in NODEUIPOSLISTSD, which is equal to the click bool Mainwindow::isnodeuiclicked () {int i=-1;    Qlist<qgraphicsitem *> items = Scene->selecteditems ();        if (items.count () = = 1) {qpointf pos = Items.first ()->pos ();        nodeui* node_temp = Dynamic_cast<nodeui *> (Items.first ());            if (Pos ==nodeuiposlists.at (i)) {//emit nodeuiclicked (node_temp);            Qmessagebox::information (This, "New window", "would open:" +node_temp->getmytext ());        return true; }} return false;}    void Mainwindow::nodeuisizeadjust () {quint16 i=0;        foreach (nodeui* node,nodeuilists) {//qdebug () << "i=" <<i;        qpointf Pos=node->pos ();        Pos.setx (Node->pos (). x () +MYNODEUI_SIZE/2);        Pos.setx (Node->pos (). x () +node->pixmap (). width ()); IfPos.x () >=0 && pos.x () &LT;=SCREEN_SIZE/2) {//(mynodeui_size-mynodeui_size_m)/(SCREEN_SIZE/2) =            = (size-20)/pos.x () quint16 size=pos.x ()/5+20;            Qpixmap pixmap = nodeuipixmaplists.at (i);            Qpixmap pixmap = nodeuilists.at (i)->pixmap ();            Pixmap = pixmap.scaled (Size,size,qt::ignoreaspectratio, qt::smoothtransformation);        Nodeuilists[i]->setpixmap (PIXMAP); }//if (Pos.x () &GT;SCREEN_SIZE/2 && pos.x () <=screen_size) if (pos.x () &GT;SCREEN_SIZE/2 && p            Os.x () <=screen_size+10) {//(mynodeui_size-mynodeui_size_m)/(SCREEN_SIZE/2) = = (size-20)/pos.x ()            Quint16 size= (Screen_size-pos.x ())/5+20;            Qpixmap pixmap = nodeuipixmaplists.at (i);            Qpixmap pixmap = nodeuilists.at (i)->pixmap ();            Pixmap = pixmap.scaled (Size,size,qt::ignoreaspectratio, qt::smoothtransformation);        Nodeuilists[i]->setpixmap (PIXMAP); }        i++; }}mainwindow::~mainwindow () {}//Gets the device resolution of a message void Mainwindow::getscreeninfo () {qdesktopwidget* Desktopwidget =    Qapplication::d esktop ();    Get the available desktop size//qrect Deskrect = Desktopwidget->availablegeometry ();    Get device screen size qrect screenrect = Desktopwidget->screengeometry ();    Sceensizex = Screenrect.width ();    Sceensizey = Screenrect.height (); Gets the number of screens set by the system (the screen is copied this value is 1)//g_nscreencount = Desktopwidget->screencount ();}
And finally the main.cpp.

Instantiate MainWindow

#include <QtGui/QApplication> #include "mainwindow.h" int main (int argc, char *argv[]) {    qapplication a (argc, ARGV);    MainWindow W;    W.setwindowopacity (1);    W.setwindowflags (qt::framelesswindowhint);    W.setattribute (qt::wa_translucentbackground);    W.show ();    W.showfullscreen ();    return a.exec ();}

Probably all wrote the note, in fact, look at a name also probably understand its role, write this program encountered problems are recorded in the previous QT study Note (iv), record, for a rainy day

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.