本文实例为大家分享了Qt自定义图形实现拖拽效果的具体代码,供大家参考,具体内容如下
在这里自定义图形是通过QPaintEvent事件绘画的图形,也可以通过自定义控件的方式添加到qt中。
首先定义类来自定义图形,这里通过paintEvent事件来实现(主要就是绘画一个图形)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
void QEventView::paintEvent(QPaintEvent *event)
{
resize(115+m_iLen,36);
QPainter painter( this );
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::blue);
//定义箭头的坐标
static const QPoint pointArr[7] =
{
QPoint(0,10),
QPoint(100+m_iLen,10),
QPoint(100+m_iLen,0),
QPoint(115+m_iLen,18),
QPoint(100+m_iLen,36),
QPoint(100+m_iLen,26),
QPoint(0,26)
};
int i = 0;
while (i < 7)
{
if (i == 6)
painter.drawLine(pointArr[i],pointArr[0]);
else
painter.drawLine(pointArr[i],pointArr[i+1]);
i++;
}
painter.drawText(QPoint(0,22),m_sEventName);
}
|
接着,主窗口程序通过mousePressEvent() mouseMoveEvent(),实现拖拽移动,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
void MainWindow::mousePressEvent(QMouseEvent *event)
{
qDebug()<< " 1:" <<event->pos();
//获取控件的对象
m_pTempWidget = childAt(event->pos());
qDebug()<<m_pTempWidget;
if (!m_pTempWidget || m_pTempWidget == centralWidget())
return ;
//容器存储自定义图形指针,以及图形的位置
QMap<QEventView*,QPoint>::iterator iter = m_mapEventPoint.begin();
while (iter != m_mapEventPoint.end())
{
if (iter.key() == m_pTempWidget)
{
m_windowInitPoint = iter.key()->frameGeometry().topLeft();
m_StartPoint = event->pos();
break ;
}
++iter;
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QMap<QEventView*,QPoint>::iterator iter = m_mapEventPoint.begin();
while (iter != m_mapEventPoint.end())
{
if (iter.key() == m_pTempWidget)
{
QPoint distance = event->pos() - m_StartPoint;
iter.key()->move(m_windowInitPoint + distance);
break ;
}
++iter;
}
}
|
就能实现简单的拖拽功能,效果图如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Fallinlove520/article/details/104244353