我想在 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);
你能告诉我哪里出了问题吗?
谢谢。
最佳答案
原因
在您的情况下,您不能移动按钮,因为尽管您已使代理可移动,但按钮以不同方式处理鼠标输入以实现其单击 功能。换句话说,在按下鼠标时,如何区分移动 Action 和点击 Action ?
解决方案
我的解决方案是使按钮成为更大的QGraphicsRectItem 的一部分。后者将用作可拖动 handle ,即如果用户与按钮交互 - 它会点击,但如果与 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
很重要。
关于c++ - 如何移动 QGraphicsView 中的 QWidget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997443/