如何在主窗口中响应点击QGraphicsItem?

duanchangping 2017-05-31 02:47:02
各位,我的程序是这样的,在主窗口放置了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);
}


...全文
278 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
七匹读书狼 2019-10-30
  • 打赏
  • 举报
回复
兄弟咋解决的啊,我也是在场景中添加自定义的Item,可以实现鼠标对Item的拖动,但是怎么实现鼠标单击item就选中呀
duanchangping 2017-05-31
  • 打赏
  • 举报
回复
已经解决了!!

16,173

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧