各位,我的程式是這樣的,在主視窗放置了QGraphicsView控制元件,并通過重寫QGraphicsItem在畫了多個item,現在的問題是我如果點擊所畫的item,該如何操作才能在主視窗中回應該點擊,現在能做到的僅僅只能在QGraphicsItem回應各種滑鼠操作,該如何反映到主視窗中?看網上的資料要重寫QGraphicsView的滑鼠事件,但是試了好久依然沒有成功,請教各位該如何操作?謝謝各位了!
代碼如下:
class VpOffest : public QMainWindow
{
Q_OBJECT
public:
VpOffest(QWidget *parent = 0);
~VpOffest();
public:
void paintEvent(QPaintEvent *event);
public:
QGraphicsScene *scene;
MyItem *itemPic;
private:
Ui::VpOffestClass ui;
};
VpOffest::VpOffest(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
void VpOffest::paintEvent(QPaintEvent *event)
{
if (!ifSceneEmpty)
{
scene->destroyed();
drawPointToDlg();
}
}
int VpOffest::drawPointToDlg()
{
scene = new QGraphicsScene(this);
scene->setSceneRect(0, 0, ui.g_grafic->geometry().width(), ui.g_grafic->geometry().height());
………
itemPic = new MyItem(xVal, yVal);
itemPic->setPos(xVal, yVal);
scene->addItem(itemPic);
}
ui.g_grafic->setScene(scene);
ifSceneEmpty = false;
return 0;
}
class MyItem : public QGraphicsItem
{
Q_OBJECT
public:
MyItem(int, int);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget);
public:
int xVal, yVal;
QGraphicsItem *currentItem;
QGraphicsItem *lastItem;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
};
#endif // MYITEM_H
MyItem::MyItem(int x, int y)
{
this->xVal = x;
this->yVal = y;
setFlag(QGraphicsItem::ItemIsFocusable);
setFlag(QGraphicsItem::ItemIsSelectable);
}
QRectF MyItem::boundingRect() const
{
return QRectF(0, 0, 15 * globalPara::zoomScale, 15 * globalPara::zoomScale);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
QRectF rect = boundingRect();
painter->drawEllipse(0, 0, 15 * globalPara::zoomScale, 15 * globalPara::zoomScale);
}
void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
currentItem = QGraphicsItem::focusItem();
int x = currentItem->x();
int y = currentItem->y();
QGraphicsItem::mousePressEvent(event);
}
uj5u.com熱心網友回復:
已經解決了!!uj5u.com熱心網友回復:
兄弟咋解決的啊,我也是在場景中添加自定義的Item,可以實作滑鼠對Item的拖動,但是怎么實作滑鼠單擊item就選中呀轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/94212.html
標籤:Qt
上一篇:多個組件共用一套廣播的問題
下一篇:qt打包程式后另存為失敗
