如何拖放自定义小部件? [英] How to Drag and Drop Custom Widgets?
问题描述
我已经创建了自己的自定义窗口小部件,我想支持内部拖放的小部件。
I have created my own custom widget and I want to support internal drag and drop for the widgets.
我已经在垂直框中添加了4个我的自定义小部件布局。现在我想在内部拖放自定义小部件。要更清楚,如果我拖动最后一个小部件并将其放在第一个位置,则第一个小部件必须移动到第二个位置,并且最后一个小部件(被拖动)必须移动到第一个位置。 (与列表视图中的项目拖放相同)。任何人都可以建议我拖放自定义小部件。
I have added 4 of my custom widgets in a vertical box layout. Now i want to drag and drop the custom widgets internally. To be more clear, If i drag the last widget and drop it in the first position, then the first widget has to move to the second positon and the last widget (which is dragged) has to move to first position. (same like drag and drop of the items in the List view). Can anyone suggest me a way to drag and drop of the custom widgets.
推荐答案
您需要重新实现 mousePressEvent
, mouseMoveEvent
和 mouseReleaseEvent
您要在其上拖动或安装事件过滤器的小部件的方法。
将光标位置存储在 mousePressEvent
,并将 mousePressEvent
中的小部件移动到光标从压点移动的距离。不要忘记在 mouseReleaseEvent
中清除光标位置。确切的代码取决于您希望小部件在拖动时的外观以及其他小部件在拖放该部件时的行为。在最简单的情况下,它将如下所示:
You need to reimplement mousePressEvent
, mouseMoveEvent
and mouseReleaseEvent
methods of a widget you want to drag or install an event filter on them.
Store the cursor position in mousePressEvent
and move the widget in mousePressEvent
to the distance the cursor moved from the press point. Don't forget to clear the cursor position in the mouseReleaseEvent
. The exact code depends of how you want the widget to look when is being dragged and how other widgets should behave when drag/drop the widget. In the simplest case it will look like this:
void mousePressEvent(QMouseEvent* event)
{
m_nMouseClick_X_Coordinate = event->globalX();
m_nMouseClick_Y_Coordinate = event->globalY();
};
void mouseMoveEvent(QMouseEvent* event)
{
if (m_nMouseClick_X_Coordinate < 0)
return;
const int distanceX = event->globalX() - m_nMouseClick_X_Coordinate;
const int distanceY = event->globalY() - m_nMouseClick_Y_Coordinate;
move(x() + distanceX, y() + distanceY());
};
void mouseReleaseEvent(QMouseEvent* event)
{
m_nMouseClick_X_Coordinate = -1;
}
这篇关于如何拖放自定义小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!