myitem.h
#ifndef MYITEM_H
#define MYITEM_H
#include <QGraphicsItem>
#include <QPainter>
class MyItem : public QGraphicsItem
{
Q_OBJECT
public:
MyItem(QObject *parent = 0);
~MyItem();
protected:
QRectF boundingRect() const;
void paint(QPainter *,const QStyleOptionGraphicsItem *,QWidget *);
};
#endif // MYITEM_H
myitem.cpp
#include "myitem.h"
MyItem::MyItem(QObject *parent) :
QGraphicsItem(parent) //这里总是报错:no matching function for call to 'QGraphicsItem::QGraphicsItem(QObject*&),求解
{
}
MyItem::~MyItem()
{
}
QRectF MyItem::boundingRect() const
{
qreal penWidth=1;
return QRectF(0-penWidth/2,0-penWidth/2,20+penWidth,20+penWidth);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
painter->setBrush(Qt::red);
painter->drawRect(0,0,20,20);
}
main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsView>
#include <QDebug>
#include "myitem.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QTransform transForm;
QGraphicsScene scene;
MyItem *item=new MyItem;
scene.addItem(item);
//qDebug()<<scene.itemAt(50,50,transForm)<<endl;
QGraphicsView view(&scene);
view.setForegroundBrush(QBrush(QColor(255,255,255,100)));
view.setBackgroundBrush(QBrush(QPixmap(":/green.jpg")));
view.resize(400,300);
view.show();
return app.exec();
}
------解决方案--------------------
是的,你看你这里函数声明:
void paint(QPainter *,const QStyleOptionGraphicsItem *,QWidget *);
再看看你的函数定义:
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
painter->setBrush(Qt::red);
painter->drawRect(0,0,20,20);
}
你应该把函数这样声明:
void paint(QPainter *painter,const QStyleOptionGraphicsItem *,QWidget *);