本文共 2743 字,大约阅读时间需要 9 分钟。
相当于N 张图片叠加起来使用,先绘制其他图片,因为只有有效区域的Alpha值为0xff,其他为0x00,这样就不会显示出来,同时不会响应鼠标事件。
必须要先绘制子items,再绘制背景,防止背景将items盖住。
如果items和background items的尺寸一致的话,可以适应窗体的缩放。
#ifndef ZGRAPHICSITEM_H
#define ZGRAPHICSITEM_H #include <QObject> #include <QGraphicsPixmapItem> #include <QGraphicsSceneMouseEvent> class ZGraphicsItem : public QObject,public QGraphicsPixmapItem { Q_OBJECT public: explicit ZGraphicsItem(QGraphicsItem *parent = 0); protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); signals: void ZSignalClicked(); public slots: }; #endif // ZGRAPHICSITEM_H #include "zgraphicsitem.h" #include <QCursor> ZGraphicsItem::ZGraphicsItem(QGraphicsItem *parent) : QGraphicsPixmapItem(parent) { } void ZGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(event->button()==Qt::LeftButton) { emit this->ZSignalClicked(); } QGraphicsPixmapItem::mousePressEvent(event); }#ifndef ZWIDGET_H
#define ZWIDGET_H #include <QWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsItem> #include <QHBoxLayout> #include <zgraphicsitem.h> class ZWidget : public QWidget { Q_OBJECT public: ZWidget(QWidget *parent = 0); ~ZWidget(); private slots: void ZSlotLeftTopClicked(); private: QGraphicsScene *m_Scene; QGraphicsView *m_view; QVBoxLayout *m_vlayoutMain; //background item. ZGraphicsItem *m_BackItem; ZGraphicsItem *m_LeftTopItem; ZGraphicsItem *m_ZiMuCeShiItem; }; #endif // ZWIDGET_H #include "zwidget.h" #include <QDebug> ZWidget::ZWidget(QWidget *parent) : QWidget(parent) { this->m_Scene=new QGraphicsScene; this->m_view=new QGraphicsView(this->m_Scene); //here we must create action-sensitive item first, //at the last draw the background to avoid hide others items. this->m_LeftTopItem=new ZGraphicsItem; this->m_LeftTopItem->setPixmap(QPixmap(":/images/zuoshangjiao.png")); connect(this->m_LeftTopItem,SIGNAL(ZSignalClicked()),this,SLOT(ZSlotLeftTopClicked())); this->m_Scene->addItem(this->m_LeftTopItem); this->m_ZiMuCeShiItem=new ZGraphicsItem; this->m_ZiMuCeShiItem->setPixmap(QPixmap(":/images/zimuceshi.png")); connect(this->m_ZiMuCeShiItem,SIGNAL(ZSignalClicked()),this,SLOT(ZSlotLeftTopClicked())); this->m_Scene->addItem(this->m_ZiMuCeShiItem); //create items. this->m_BackItem=new ZGraphicsItem; this->m_BackItem->setPixmap(QPixmap(":/images/background.png")); this->m_Scene->addItem(this->m_BackItem); //layout main. this->m_vlayoutMain=new QVBoxLayout; this->m_vlayoutMain->addWidget(this->m_view); this->setLayout(this->m_vlayoutMain); } ZWidget::~ZWidget() { delete this->m_view; delete this->m_BackItem; delete this->m_LeftTopItem; delete this->m_ZiMuCeShiItem; delete this->m_Scene; delete this->m_vlayoutMain; } void ZWidget::ZSlotLeftTopClicked() { static int i=0; qDebug()<<"clicked:"<<i++; }