qt学习笔记(五) QGraphicsPixmapItem与QGraphicsScene的编程实例 图标拖动渐变效果

应大家的要求,还是把完整的project文件贴出来,大家省点事:http://www.kuaipan.cn/file/id_48923272389086450.htm

先看看执行效果,我用的群创7寸屏,主机是mini2440,分辨率是800*480,程序写比較粗糙,但对刚開始学习的人还是有一点启示,大家一起进步。

qt中提供了QGphicsView,QGraphicsScene,QGraphicsItem,QGraphicsPixmapItem是QGraphicsItem的子类

分辨创建它们的实例:view,scene,item,然后通过各自的方法scene->addItem(item);view->setScene(scene);就能够达到类似下图的效果,想要进一步定制,则要继承QGraphicsItem或QGraphicsPixmapItem,然后重写paint()、boundingRect()等方法,此外假设还想要获取鼠标事件,重写mousePressEvent等事件就好了,注意,一旦重写了mousePressEvent方法,就以为了qt不会再自己主动处理item的不论什么press事件了,能够在你重写的mousePressEvent方法中最后加入?QGraphicsItem::mousePressEvent(event);解决问题,就是说你获取到了鼠标事件,可是依旧让qt处理这个鼠标事件。

程序中的item能够水平拖动,拖动的同一时候图标大小会渐变,中间最大,两边渐小。

图1

图2

图3

以下是源程序文件夹结构:

mainwindow.h与main.cpp是qt自己主动产生的代码,我没有产生窗体ui

myscene.h与某与scene.cpp是定义了类MyScene,继承自QGraphicsScene,我的目的是要获取其鼠标事件

nodeui.h与nodeui.cpp是定义了类NodeUI,继承自QGraphicsPixmapItem,目的相当多。

以下详细的源文件:myscene.h与myscene.cpp相对简单,就实现了一个功能

myscene.h

#ifndef MYSCENE_H
#define MYSCENE_H

#include <QGraphicsScene>

class MyScene : public QGraphicsScene
{
Q_OBJECT
public:
    explicit MyScene(QObject *parent = 0);

private:
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

signals:
    void isMoving(QPointF &pos);

public 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();
}

再看nodeui.h与nodeui.cpp,在原来的QGraphicsPixmapItem基础上又假如了点自己的东西

#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_OBJECT
public:
    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();

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
private:
    //QString myImage;
    QString myText;

};

#endif // NODEUI_H

nideui.cpp

#include "nodeui.h"
#include <QPixmap>
#include <iostream>
#include <QDebug>

NodeUI::NodeUI()
{
}
/*note: imagesize = 80 is in the nodeui.h*/
NodeUI::NodeUI(QString &file,QString &text,int imagesize)
{

    setMyText(text);
    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::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
           QWidget *widget)
{
    QPixmap pixmap = 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(),15),Qt::AlignCenter,myText);

    if (option->state & QStyle::State_Sunken)
    {
        QRectF rect1 = boundingRect();
        //QPen pen(Qt::darkGreen);
        painter->setPen(QPen(Qt::darkGreen));
    }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;
}

最后是scene与item的文件mainwindow.cpp,继承了QMainWindow,作用就是画一个应用程序框架

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_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

    NodeUI *selectedNodeUI();
    bool isNodeUiClicked();
    void nodeUiSizeAdjust();
    //var

protected:

private:

    void GetScreenInfo();
    QGraphicsView *view;
    //QGraphicsScene *scene;
    MyScene *scene;
    //instead of (NodeUI *nodeui;)&(QPointF nodeUiPos;)
    //眼下弃用,因为QMap的顺序无法人为设定,依照内部key自己主动升序
    //QMap<NodeUI*,QPointF>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;
    */
    //弃用
    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)
{
    //初始化
    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());

    //又一次计算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++;
    }

    //用于button的单机

    view->setScene(scene);
    //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"));
}
//槽,当scene鼠标拖拽是运行
//控制UI图标的水平
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();
    }
}
//槽,当nodeui鼠标按下时运行,调用selectedNodeUI函数,更新currentNodeUI变量
//除此之外,selectionChanged()也是一个槽,由scene调用
void MainWindow::isPressed()
{
    selectionChanged();
    mPressed = true;
}
//槽,当nodeui鼠标释放时运行
//应当设置标志位,让UI图片停止对鼠标拖动事件的响应
void MainWindow::isReleased()
{
    mPressed = false;
    if(isNodeUiClicked())
        qDebug()<<"clicked";
    qDebug()<<"release";
}

//槽,当scene的selectedItem变化时,发送同名信号到此槽
void MainWindow::selectionChanged()
{
    int i=0,j=0;
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1) {
        //当前所选择的UI图标的坐标
        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;
    }
}
//推断是否Nodeui接收的是否是单击信号。
//推断根据是当前单击的nodeui对象的pos与存储在nodeUiPosListsd的位置比較,相等则为单击
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","will 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());
        if(pos.x()>=0 && pos.x()<=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()>SCREEN_SIZE/2 && pos.x()<=SCREEN_SIZE)
        if(pos.x()>SCREEN_SIZE/2 && pos.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()
{
}
//获取设备分辨率的呢个信息
void MainWindow::GetScreenInfo()
{
    QDesktopWidget* desktopWidget = QApplication::desktop();
    //获取可用桌面大小
    //QRect deskRect = desktopWidget->availableGeometry();
    //获取设备屏幕大小
    QRect screenRect = desktopWidget->screenGeometry();

    sceenSizeX = screenRect.width();
    sceenSizeY = screenRect.height();

    //获取系统设置的屏幕个数(屏幕拷贝方式该值为1)
    //g_nScreenCount = desktopWidget->screenCount();
}

最后是main.cpp

实例化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();
}

大概都写了注解了,事实上看看一个名称也该大概了解其作用,写这程序时遇到的问题都记录在了前一篇qt学习笔记(四)中,记录一下,以备不时之需

时间: 2024-10-01 18:48:01

qt学习笔记(五) QGraphicsPixmapItem与QGraphicsScene的编程实例 图标拖动渐变效果的相关文章

【Qt学习笔记】2.窗体Widget && 屏幕坐标 && 布局

一.窗体 在Qt中,把窗体(口)叫做Widget. Widget可以是主窗体(口),也可以是依附在主窗体(口)上的各种控件,作为子窗体,这两种窗口,分别称作顶级窗口(top-level widget)和子窗口(sub widget). 顶级窗口:一个标准的窗口,带边框.标题栏.若干按钮.(独立) 子窗口:在窗口里面的窗口,例如:按钮.文本框等控件.(不独立,随着父窗口移动) 注意: 1.每个子窗口都有一个父窗口 2.子窗口里面可能包含了若干子窗口,是一层一层的关系. 3.顶级窗口也有父窗口:就是

Caliburn.Micro学习笔记(五)----协同IResult

Caliburn.Micro学习笔记(五)----协同IResult 今天说一下协同IResult 看一下IResult接口 /// <summary> /// Allows custom code to execute after the return of a action. /// </summary> public interface IResult { /// <summary> /// Executes the result using the specif

angular学习笔记(五)-阶乘计算实例(1)

<!DOCTYPE html> <html ng-app> <head> <title>2.3.2计算阶乘实例1</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </

【Qt学习笔记】13.拖放技术:Drag & Drop

1.接受拖放 Drag & Drop 是一个界面操作,用于在两个窗口间传递数据. Drag Source: 拖放源窗口 Drag Target: 拖放目标窗口 拖放操作: 1.在源窗口:选中目标,按下鼠标,移动,拖至目标窗口(Drag) 2.在目标窗口:取消鼠标,到指定位置,松开鼠标(Drop) (按下ESC取消操作) MIME: MIME(Multipurpose Internet Mail Extensions)被传递的数据以MIME格式传送,它是多组type-data数据:(type0,

QT学习笔记—1

1.模态和非模态的区别:非模态可以同时操作两个窗口,模态的只能在顶层窗口关闭之后才能使用其他窗口 //同时显示出widget和dialog窗口,非模态     QDialog *dialog = new QDialog(this);     dialog->show(); //同时显示出widget和dialog窗口,模态     QDialog *dialog = new QDialog(this);     dialog->setModal(true);     dialog->sh

NLTK学习笔记(五):分类和标注词汇

[TOC] 词性标注器 之后的很多工作都需要标注完的词汇.nltk自带英文标注器pos_tag import nltk text = nltk.word_tokenize("And now for something compleyely difference") print(text) print(nltk.pos_tag(text)) 标注语料库 表示已经标注的标识符:nltk.tag.str2tuple('word/类型') text = "The/AT grand/J

Qt学习笔记-Widget布局管理

Qt学习笔记4-Widget布局管理 以<C++ GUI Programming with Qt 4, Second Edition>为参考 实例:查找对话框 包含三个文件,finddialog.h,finddialog.cpp及main.cpp. //finddialog.h代码 #ifndef FINDDIALOG_H#define FINDDIALOG_H #include <QDialog> class QCheckBox;class QLabel;class QLineE

Linux System Programming 学习笔记(五) 进程管理

1. 进程是unix系统中两个最重要的基础抽象之一(另一个是文件) A process is a running program A thread is the unit of activity inside of a process the virtualization of memory is associated with the process, the threads all share the same memory address space 2. pid The idle pro

java之jvm学习笔记五(实践写自己的类装载器)

java之jvm学习笔记五(实践写自己的类装载器) 课程源码:http://download.csdn.net/detail/yfqnihao/4866501 前面第三和第四节我们一直在强调一句话,类装载器和安全管理器是可以被动态扩展的,或者说,他们是可以由用户自己定制的,今天我们就是动手试试,怎么做这部分的实践,当然,在阅读本篇之前,至少要阅读过笔记三. 下面我们先来动态扩展一个类装载器,当然这只是一个比较小的demo,旨在让大家有个比较形象的概念. 第一步,首先定义自己的类装载器,从Clas