实例QT程序 —— QTableWidget 表格行的上下移动

目录

1.简介
2.源码
3.效果图



1.简介

实例QT程序:实现QTableWidget表格中行的上移/下移的功能。

2.源码

widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class QTableWidget;

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_btnUp_clicked();

    void on_btnDown_clicked();

private:
    // 移动行
    void moveRow( QTableWidget *pTable, int nFrom, int nTo );

    // 复制行
    void copyRow( QTableWidget *pTable, int nFrom, int nTo );

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.cpp
#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->tabWdg->selectRow(0);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btnUp_clicked()
{
    int nCurRow = ui->tabWdg->currentRow();
    moveRow(ui->tabWdg, nCurRow, nCurRow-1);
}

void Widget::on_btnDown_clicked()
{
    int nCurRow = ui->tabWdg->currentRow();
    moveRow(ui->tabWdg, nCurRow, nCurRow+1);
}

void Widget::copyRow( QTableWidget *pTable, int nFrom, int nTo )
{
    int nColCount = pTable->columnCount();
    for(int col=0; col<nColCount; col++){
        QString text = pTable->item(nFrom, col)->text();
        QTableWidgetItem *it = new QTableWidgetItem;
        it->setText(text);
        pTable->setItem(nTo, col, it);
    }
}

void Widget::moveRow( QTableWidget *pTable, int nFrom, int nTo )
{
    if( pTable == nullptr ) {
        return;
    }
    if( nFrom == nTo ) {
        return;
    }
    if( nFrom < 0 || nTo < 0 ) {
        return;
    }
    int nRowCount = pTable->rowCount();
    if( nFrom >= nRowCount  || nTo >= nRowCount ) return;

    int nColCur = 0;
    nColCur = pTable->currentColumn();
    QTableWidgetItem *itCur = pTable->currentItem();
    if( nullptr != itCur ){
        nColCur = itCur->column();
    }
    int nFromRow = nFrom;
    int nInsertRow = nTo;
    if( nTo < nFrom ){  // Up
        nFromRow = nFrom + 1;
        pTable->insertRow(nTo);
//        this->insertRow(pTable, nTo);
    }else { // Down
        nInsertRow = nTo + 1;
        pTable->insertRow(nInsertRow);
//        this->insertRow(pTable, nInsertRow);
    }
    this->copyRow( pTable, nFromRow, nInsertRow );
//    this->removeRow( pTable, nFromRow );   //删除旧行信息
    pTable->removeRow(nFromRow);

    // 选择之前移动的行
    pTable->selectRow( nInsertRow );
    pTable->setCurrentCell(nTo, nColCur);
}

3.效果图

运行效果图
运行效果图




加油,向未来!GO~
Come on


发布了18 篇原创文章 · 获赞 3 · 访问量 3954

猜你喜欢

转载自blog.csdn.net/Redboy_Crazy/article/details/105128822
今日推荐