写了一个 【QWidget 保持原有行为, 且被添加到 QGraphicsScene, 同时可以在按住Ctrl时 进行移动】 的代码。
试验成功,但不知是否存在【某种隐患】,忘有经验的朋友,指正下~~
- class XGraphicsProxyWidget : public QGraphicsProxyWidget
- {
- public:
- XGraphicsProxyWidget (QGraphicsItem* parent = 0, Qt::WindowFlags wFlags = 0);
- void SetGraphicsMode(GraphicsItemFlags);
- protected:
- void mousePressEvent(QGraphicsSceneMouseEvent*);
- void mouseReleaseEvent(QGraphicsSceneMouseEvent*);
- void mouseMoveEvent(QGraphicsSceneMouseEvent*);
- private:
- void StartGraphicsMode();
- void StopGraphicsMode();
- bool IsGraphicsMode() const;
- private:
- GraphicsItemFlags m_eWidgetFlag;
- GraphicsItemFlags m_eGraphicsFlag;
- };
- XGraphicsProxyWidget::XGraphicsProxyWidget( QGraphicsItem * parent /* = 0 */, Qt::WindowFlags wFlags /* = 0 */ ) :
- QGraphicsProxyWidget(parent, wFlags),
- m_eWidgetFlag(flags()),
- m_eGraphicsFlag(0)
- {
- }
- void XGraphicsProxyWidget::SetGraphicsMode(GraphicsItemFlags flags)
- {
- m_eGraphicsFlag = flags;
- }
- void XGraphicsProxyWidget::StartGraphicsMode()
- {
- m_eWidgetFlag = flags(); // save
- setFlags(m_eGraphicsFlag);
- }
- void XGraphicsProxyWidget::StopGraphicsMode()
- {
- setFlags(m_eWidgetFlag);
- }
- bool XGraphicsProxyWidget::IsGraphicsMode() const
- {
- return flags() == m_eGraphicsFlag;
- }
- void XGraphicsProxyWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
- {
- if (event->type() == QEvent::GraphicsSceneMousePress
- && (event->modifiers() & Qt::ControlModifier))
- {
- StartGraphicsMode();
-
- QGraphicsItem::mousePressEvent(event);
- }
- else
- {
- QGraphicsProxyWidget::mousePressEvent(event);
- }
- }
- void XGraphicsProxyWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
- {
- if (IsGraphicsMode())
- {
- StopGraphicsMode();
- QGraphicsItem::mouseReleaseEvent(event);
- }
- else
- {
- QGraphicsProxyWidget::mouseReleaseEvent(event);
- }
- }
- void XGraphicsProxyWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
- {
- if (IsGraphicsMode())
- QGraphicsItem::mouseMoveEvent(event);
- else
- QGraphicsProxyWidget::mouseMoveEvent(event);
- }
测试代码:
- m_pScene = new QGraphicsScene;
- m_pView = new QGraphicsView(m_pScene, this);
- //m_pView->resize(800, 600);
- setCentralWidget(m_pView);
- QLineEdit* pb = new QLineEdit("text");
- XGraphicsProxyWidget *proxy = new XGraphicsProxyWidget;
- proxy->setWidget(pb);
- proxy->SetGraphicsMode(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
- m_pScene->addItem(proxy);
- m_pView->show();
因为先点击控件, 后按 ctrl , QWidget状态会有
错误(以QPushButton为例),因此只能做成【必须先按ctrl,再点击QGraphicItem才能移动】。不知道是否有更好的方法可以解决这种现象~~