實例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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章