Qt拖拽效果 Qt自定义图形实现拖拽效果
Tjmies 人气:2想了解Qt自定义图形实现拖拽效果的相关内容吗,Tjmies在本文为您仔细讲解Qt拖拽效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Qt,拖拽,下面大家一起来学习吧。
在这里自定义图形是通过QPaintEvent事件绘画的图形,也可以通过自定义控件的方式添加到qt中。
首先定义类来自定义图形,这里通过paintEvent事件来实现(主要就是绘画一个图形)
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(),实现拖拽移动,
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; } }
就能实现简单的拖拽功能,效果图如下:
加载全部内容