C/C++ Qt TableDelegate 自定義代理元件

lyshark發表於2021-12-01

TableDelegate 自定義代理元件的主要作用是對原有表格進行調整,例如預設情況下Table中的預設代理就是一個編輯框,我們只能夠在編輯框內輸入資料,而有時我們想選擇資料而不是輸入,此時就需要重寫編輯框實現選擇的效果,代理元件常用於個性化定製Table表格中的欄位型別。

在自定義代理中QAbstractItemDelegate是所有代理類的抽象基類,我們繼承任何元件時都必須要包括如下4個函式:

  • CreateEditor() 用於建立編輯模型資料的元件,例如(QSpinBox元件)
  • SetEditorData() 從資料模型獲取資料,以供Widget元件進行編輯
  • SetModelData() 將Widget元件上的資料更新到資料模型
  • UpdateEditorGeometry() 給Widget元件設定一個合適的大小

此處我們分別重寫三個代理介面,其中兩個ComBox元件用於選擇婚否,SpinBox元件用於調節數值範圍,先來定義三個重寫部件。

重寫介面spindelegate.cpp程式碼如下.

#include "spindelegate.h"
#include <QSpinBox>

QWIntSpinDelegate::QWIntSpinDelegate(QObject *parent):QStyledItemDelegate(parent)
{
}

// https://www.cnblogs.com/lyshark
QWidget *QWIntSpinDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//建立代理編輯元件
    Q_UNUSED(option);
    Q_UNUSED(index);

    QSpinBox *editor = new QSpinBox(parent); //建立一個QSpinBox
    editor->setFrame(false); //設定為無邊框
    editor->setMinimum(0);
    editor->setMaximum(10000);
    return editor;  //返回此編輯器
}

void QWIntSpinDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{
//從資料模型獲取資料,顯示到代理元件中
//獲取資料模型的模型索引指向的單元的資料
    int value = index.model()->data(index, Qt::EditRole).toInt();

    QSpinBox *spinBox = static_cast<QSpinBox*>(editor);  //強制型別轉換
    spinBox->setValue(value); //設定編輯器的數值
}

void QWIntSpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
//將代理元件的資料,儲存到資料模型中
    QSpinBox *spinBox = static_cast<QSpinBox*>(editor); //強制型別轉換
    spinBox->interpretText(); //解釋資料,如果資料被修改後,就觸發訊號
    int value = spinBox->value(); //獲取spinBox的值

    model->setData(index, value, Qt::EditRole); //更新到資料模型
}

void QWIntSpinDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//設定元件大小
    Q_UNUSED(index);
    editor->setGeometry(option.rect);
}

重寫介面floatspindelegate.cpp程式碼如下.

#include "floatspindelegate.h"
#include <QDoubleSpinBox>

QWFloatSpinDelegate::QWFloatSpinDelegate(QObject *parent):QStyledItemDelegate(parent)
{
}

QWidget *QWFloatSpinDelegate::createEditor(QWidget *parent,
   const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
    editor->setFrame(false);
    editor->setMinimum(0);
    editor->setDecimals(2);
    editor->setMaximum(10000);

    return editor;
}

void QWFloatSpinDelegate::setEditorData(QWidget *editor,
                      const QModelIndex &index) const
{
    float value = index.model()->data(index, Qt::EditRole).toFloat();
    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->setValue(value);
}

// https://www.cnblogs.com/lyshark
void QWFloatSpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->interpretText();
    float value = spinBox->value();
    QString str=QString::asprintf("%.2f",value);

    model->setData(index, str, Qt::EditRole);
}

void QWFloatSpinDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

重寫介面comboxdelegate.cpp程式碼如下.

#include "comboxdelegate.h"
#include <QComboBox>

QWComboBoxDelegate::QWComboBoxDelegate(QObject *parent):QItemDelegate(parent)
{
}

QWidget *QWComboBoxDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox *editor = new QComboBox(parent);

    editor->addItem("已婚");
    editor->addItem("未婚");
    editor->addItem("單身");

    return editor;
}

// https://www.cnblogs.com/lyshark
void QWComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString str = index.model()->data(index, Qt::EditRole).toString();

    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    comboBox->setCurrentText(str);
}

void QWComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    QString str = comboBox->currentText();
    model->setData(index, str, Qt::EditRole);
}

void QWComboBoxDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

將部件匯入到mainwindow.cpp中,並將其通過ui->tableView->setItemDelegateForColumn(0,&intSpinDelegate);關聯部件到指定的table下標索引上面。

#include "mainwindow.h"
#include "ui_mainwindow.h"

// https://www.cnblogs.com/lyshark
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 初始化模型資料
    model = new QStandardItemModel(4,6,this);      // 初始化4行,每行六列
    selection = new QItemSelectionModel(model);    // 關聯模型

    ui->tableView->setModel(model);
    ui->tableView->setSelectionModel(selection);

    // 新增表頭
    QStringList HeaderList;
    HeaderList << "序號" << "姓名" << "年齡" << "性別" << "婚否" << "薪資";
    model->setHorizontalHeaderLabels(HeaderList);

    // 批量新增資料
    QStringList DataList[3];
    QStandardItem *Item;

    DataList[0] << "1001" << "admin" << "24" << "男" << "已婚" << "4235.43";
    DataList[1] << "1002" << "lyshark" << "23" << "男" << "未婚" << "10000.21";
    DataList[2] << "1003" << "lucy" << "37" << "女" << "單身" << "8900.23";

    int Array_Length = DataList->length();                          // 獲取每個陣列中元素數
    int Array_Count = sizeof(DataList) / sizeof(DataList[0]);       // 獲取陣列個數

    for(int x=0; x<Array_Count; x++)
    {
        for(int y=0; y<Array_Length; y++)
        {
            // std::cout << DataList[x][y].toStdString().data() << std::endl;
            Item = new QStandardItem(DataList[x][y]);
            model->setItem(x,y,Item);
        }
    }

    // 為各列設定自定義代理元件
    // 0,4,5 代表第幾列 後面的函式則是使用哪個代理類的意思
    ui->tableView->setItemDelegateForColumn(0,&intSpinDelegate);
    ui->tableView->setItemDelegateForColumn(4,&comboBoxDelegate);
    ui->tableView->setItemDelegateForColumn(5,&floatSpinDelegate);

}

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

代理部件關聯後,再次執行程式,會發現原來的TableWidget元件中的編輯框已經替換為了選擇框等元件:

相關文章