#include <QtCore/QDebug>#include <QtGui/QApplication>#include <QtGui/QDragMoveEvent>#include <QtGui/QPainter>#include <QtGui/QTreeWidget>class TreeWidget : public QTreeWidget{public: TreeWidget( QWidget* parent = 0 ) : QTreeWidget( parent ), _dragMoveItemBelow( 0 ) { setDragDropMode( QTreeWidget::InternalMove ); } ~TreeWidget() {}private: void dragMoveEvent( QDragMoveEvent* event ) { _dragMoveLine = QLine(); event->ignore(); QTreeWidgetItem* item = itemFromIndex( indexAt( event->pos() ) ); if ( item == currentItem() ) { return; } const QRect& rect = visualRect( indexAt( event->pos() ) ); if ( rect.top() + 2 >= event->pos().y() ) { if ( currentItem() == itemAbove( item ) ) { return; } _dragMoveLine = QLine( rect.left(), rect.top(), rect.right(), rect.top() ); _dragMoveItemBelow = item; event->acceptProposedAction(); } else if ( rect.bottom() - 2 <= event->pos().y() ) { if ( currentItem() == itemBelow( item ) ) { return; } _dragMoveLine = QLine( rect.left(), rect.bottom(), rect.right(), rect.bottom() ); _dragMoveItemBelow = itemBelow( item ); event->acceptProposedAction(); } viewport()->update(); } void dropEvent( QDropEvent* ) { QTreeWidgetItem* item = currentItem(); item = takeTopLevelItem( indexOfTopLevelItem( item ) ); insertTopLevelItem( indexOfTopLevelItem( _dragMoveItemBelow ), item ); setCurrentItem( item ); _dragMoveLine = QLine(); viewport()->update(); } void paintEvent( QPaintEvent* event ) { QTreeWidget::paintEvent( event ); QPainter p( viewport() ); p.setPen( QPen( Qt::black, 2 ) ); p.drawLine( _dragMoveLine ); } QLine _dragMoveLine; QTreeWidgetItem* _dragMoveItemBelow;};int main( int argc, char** argv ){ QApplication app( argc, argv ); TreeWidget widget; widget.setColumnCount( 1 ); widget.headerItem()->setText( 0, QObject::tr( "Title" ) ); QTreeWidgetItem* item1 = new QTreeWidgetItem( &widget ); item1->setText( 0, "1" ); QTreeWidgetItem* item2 = new QTreeWidgetItem( &widget ); item2->setText( 0, "2" ); QTreeWidgetItem* item3 = new QTreeWidgetItem( &widget ); item3->setText( 0, "3" ); QTreeWidgetItem* item4 = new QTreeWidgetItem( &widget ); item4->setText( 0, "4" ); QTreeWidgetItem* item5 = new QTreeWidgetItem( &widget ); item5->setText( 0, "5" ); app.setActiveWindow( &widget ); widget.show(); return app.exec();}
void dropEvent( QDropEvent* ) { QTreeWidgetItem* item = currentItem(); item = takeTopLevelItem( indexOfTopLevelItem( item ) ); if ( _dragMoveItemBelow ) { insertTopLevelItem( indexOfTopLevelItem( _dragMoveItemBelow ), item ); } else { addTopLevelItem( item ); } setCurrentItem( item ); _dragMoveLine = QLine(); viewport()->update(); }