关于QTablewidget里的item拖拽



  • 之前做的一个项目用到tablewidget,但是当时没找到像listwidget一样可以拖拽的功能,(可能要用QTableView和QTablewidgetItem)但是那时候对QT并不熟悉,没去找,问了下别人然后用drag drop event实现了,应该不是唯一办法,反正也共享一下,水水论坛,支持一下qt dream

    源码发了可以下载,下面贴cpp的代码
    #include <MyTableWidget.h>

    #include <MyTableWidget.h>

    MyTableWidget::MyTableWidget(QWidget *parent)
    : QTableWidget(parent)
    {
    setAcceptDrops(true);
    }

    void MyTableWidget::mousePressEvent(QMouseEvent *event)
    {
    if (event->button() & Qt::RightButton)
    mousePressedPoint = event->pos();
    QTableWidget::mousePressEvent(event);
    }

    void MyTableWidget::mouseMoveEvent(QMouseEvent *event)
    {
    if (event->buttons() & Qt::RightButton) {
    const int distance = (event->pos() - mousePressedPoint).manhattanLength();
    if (distance >= QApplication::startDragDistance())
    startDrag();
    }
    QTableWidget::mouseMoveEvent(event);
    }

    void MyTableWidget::dragEnterEvent(QDragEnterEvent *event)
    {
    QTableWidgetItem *source = itemAt(mousePressedPoint);
    QTableWidgetItem *target = itemAt(event->pos());
    if (source && target) {
    event->setDropAction(Qt::MoveAction);
    event->accept();
    }
    }

    void MyTableWidget::dragMoveEvent(QDragMoveEvent *event)
    {
    QTableWidgetItem *source = itemAt(mousePressedPoint);
    QTableWidgetItem *target = itemAt(event->pos());
    if (source && target) {
    event->setDropAction(Qt::MoveAction);
    event->accept();
    }
    }

    void MyTableWidget::dropEvent(QDropEvent *event)
    {
    QTableWidgetItem *source = itemAt(mousePressedPoint);
    QTableWidgetItem *target = itemAt(event->pos());

    if(source && target &&source!=target)
    {
    
    QTableWidgetItem *source2= item(source->row(),1-source->column());
    QTableWidgetItem *target2= item(target->row(),1-target->column());
    QString string=source2->text();
    
    
    //QString aa=QString::number(string,10);
    

    // QMessageBox *mes=new QMessageBox;
    // mes->setText(string);
    // mes->show();

    if (source && target && source != target && source2 && target2 &&source2!=target2) {
        source->setText(target->text());
        target->setText(event->mimeData()->text());
    
        source2->setText(target2->text());
        target2->setText(string);
    
        event->setDropAction(Qt::MoveAction);
        event->accept();
        emit listchanged();
    }
    }
    else{return;}
    

    }

    void MyTableWidget::startDrag()
    {
    QTableWidgetItem *item = itemAt(mousePressedPoint);
    if (item) {
    QMimeData *mimeData = new QMimeData;
    mimeData->setText(item->text());
    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->exec();
    }
    }

    源码:
    .h:
    1_1453099625037_MyTableWidget.h
    .cpp:
    0_1453099625037_MyTableWidget.cpp



  • @wxxxxx 代码格式没写好,不要用中文输入法下的```。



  • @taadis 额..编辑的时候好像没问题.. 但是发上来就自动对齐左边了 - -


登录后回复
 

与 萌梦社区 的连接断开,我们正在尝试重连,请耐心等待