如何移动 QGraphicsView 中的 QWidget?
How can i move the QWidget in QGraphicsView?
我想在 QGraphicsView 中移动 QPushButton 或某种 QWidget,例如 QListWidet、QTableWidget 等。
所以,我使用了 QGraphicsProxyWidget。
然后我点击了小部件并拖动。但是它不动。
如何移动 QWidget?
这是我的代码。
ui->graphicsView->setGeometry(0,0,geometry().width(),geometry().height());
scene = new QGraphicsScene(0, 0, geometry().width(), geometry().height(), this);
ui->graphicsView->setScene(scene);
btn =new QPushButton(NULL);
QGraphicsProxyWidget *proxy = scene->addWidget(btn);
proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
scene->addItem(proxy);
你能告诉我哪里出了问题吗?
谢谢。
原因
在您的情况下,您不能移动按钮,因为虽然您已使代理可移动,但按钮以不同方式处理鼠标输入以实现其 clicked 功能。换句话说,在鼠标按下时,如何区分移动动作和点击动作?
解决方案
我的解决方案是使按钮成为更大 QGraphicsRectItem 的一部分。后者将用作可拖动手柄,即如果用户与按钮交互 - 它会点击,但如果 QGraphicsRectItem 的其他部分(未被按钮覆盖)与之交互,按钮可以移动。
示例
下面是一个示例,展示了如何做到这一点:
auto *item = new QGraphicsRectItem(0, 0, 75, 40);
auto *proxy = new QGraphicsProxyWidget(item);
auto *btn = new QPushButton(tr("Click me"));
btn->setGeometry(0, 0, 77, 26);
item->setFlag(QGraphicsItem::ItemIsMovable);
item->setBrush(Qt::darkYellow);
proxy->setWidget(btn);
proxy->setPos(0, 15);
proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
scene->addItem(item);
注意: 要完成此工作,重要的是将 proxy
的父级设置为 item
。
我想在 QGraphicsView 中移动 QPushButton 或某种 QWidget,例如 QListWidet、QTableWidget 等。
所以,我使用了 QGraphicsProxyWidget。
然后我点击了小部件并拖动。但是它不动。
如何移动 QWidget?
这是我的代码。
ui->graphicsView->setGeometry(0,0,geometry().width(),geometry().height());
scene = new QGraphicsScene(0, 0, geometry().width(), geometry().height(), this);
ui->graphicsView->setScene(scene);
btn =new QPushButton(NULL);
QGraphicsProxyWidget *proxy = scene->addWidget(btn);
proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
scene->addItem(proxy);
你能告诉我哪里出了问题吗?
谢谢。
原因
在您的情况下,您不能移动按钮,因为虽然您已使代理可移动,但按钮以不同方式处理鼠标输入以实现其 clicked 功能。换句话说,在鼠标按下时,如何区分移动动作和点击动作?
解决方案
我的解决方案是使按钮成为更大 QGraphicsRectItem 的一部分。后者将用作可拖动手柄,即如果用户与按钮交互 - 它会点击,但如果 QGraphicsRectItem 的其他部分(未被按钮覆盖)与之交互,按钮可以移动。
示例
下面是一个示例,展示了如何做到这一点:
auto *item = new QGraphicsRectItem(0, 0, 75, 40);
auto *proxy = new QGraphicsProxyWidget(item);
auto *btn = new QPushButton(tr("Click me"));
btn->setGeometry(0, 0, 77, 26);
item->setFlag(QGraphicsItem::ItemIsMovable);
item->setBrush(Qt::darkYellow);
proxy->setWidget(btn);
proxy->setPos(0, 15);
proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
scene->addItem(item);
注意: 要完成此工作,重要的是将 proxy
的父级设置为 item
。