美文网首页my-QT专栏
QT QTableview QItemDelegate 简单使用

QT QTableview QItemDelegate 简单使用

作者: c之气三段 | 来源:发表于2021-08-28 23:52 被阅读0次

    简单使用,数据不是单例且只能选择那个位置不可编辑

    QItemDelegate只能在编辑的时候显示。
    .h

    #ifndef TABLEVIEW_H
    #define TABLEVIEW_H
    
    #include <QItemDelegate>
    #include <QWidget>
    
    namespace Ui {
    class Tableview;
    }
    
    class Tableview : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit Tableview(QWidget *parent = 0);
        ~Tableview();
    private:
        Ui::Tableview *ui;
    };
    class ItemDelegate :public QItemDelegate
    {
    public:
        ItemDelegate(QObject *parent = nullptr);
    
        // QAbstractItemDelegate interface
    public:
        virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
        virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override;
        virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
        virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
    };
    #endif // TABLEVIEW_H
    
    

    .cpp

    #include "Tableview.h"
    #include "ui_Tableview.h"
    
    #include <QLineEdit>
    #include <QStandardItemModel>
    #include<qdebug.h>
    Tableview::Tableview(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::Tableview)
    {
        ui->setupUi(this);
        ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {"
                                                         "color: black;border: 1px solid #6c6c6c;}");
    //允许鼠标事件
       ui->tableView->setMouseTracking(true);
        //设置选中时为整行选中
        ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
        //铺满整个窗口
        ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        ui->tableView->verticalHeader()->setVisible(false);
        QStandardItemModel *itemModel = new QStandardItemModel(this);
        ui->tableView->setModel(itemModel);
        itemModel->setRowCount(2);
        QStringList header;header<<"1"<<"2"<<"3"<<"4"<<"5";
        itemModel->setHorizontalHeaderLabels(header);
        QStringList data;data<<"1"<<"2"<<"3"<<"4"<<"5";
        for(int i = 0;i<data.size();i++)
        {
            QStandardItem *item = new QStandardItem(data.at(i));
            item->setEditable(false);
            item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            itemModel->setItem(0,i,item);
        }
        ui->tableView->setItemDelegateForRow(1,new ItemDelegate(this));
        for(int i = 0;i<data.size();i++)
        {
            QStandardItem *item = new QStandardItem;
            item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            itemModel->setItem(1,i,item);
        }
        //获取数据
        connect(ui->pushButton,&QPushButton::clicked,this,[=](){
            for(int i = 0;i<data.size();i++)
            {
                qDebug()<<itemModel->index(1,i).data().toString();
            }
        });
    //指定位置添加控件,未编辑也显示
        QPushButton *button_1 = new QPushButton(this);
        button_1->setText("123");
        ui->tableView->setIndexWidget(itemModel->index(2,2),button_1);
    }
    
    Tableview::~Tableview()
    {
        delete ui;
    }
    
    ItemDelegate::ItemDelegate(QObject *parent):QItemDelegate(parent)
    {
    
    }
    
    QWidget *ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        Q_UNUSED(option)
        Q_UNUSED(index)
        QLineEdit *editor = new QLineEdit(parent);
        editor->setAlignment(Qt::AlignCenter);
        QRegExp regx("[0-9]+$");
        QValidator *validator=new QRegExpValidator(regx,editor);
        editor->setValidator(validator);
        return editor;
    }
    
    void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
    {
        QString value = index.model()->data(index, Qt::EditRole).toInt();
        QLineEdit *currentEditor = static_cast<QLineEdit*>(editor);
        currentEditor->setText(value);
    }
    
    void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
    {
        QLineEdit *currentEditor = static_cast<QLineEdit*>(editor);
        QString value= currentEditor->text();
        //设置模型的数据
        model->setData(index, value, Qt::EditRole);
    }
    
    void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        //根据option,设置编辑框位置
        Q_UNUSED(index)
        editor->setGeometry(option.rect);
    }
    

    未编辑也显示控件,不过要为单元格分类,除非指定行或者列全是代理。
    .h

    class ItemDelegate :public QItemDelegate
    {
    public:
        ItemDelegate(QObject *parent = nullptr);
        // QAbstractItemDelegate interface
        virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
        virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override;
    private:
        QPushButton *m_boutton;
    };
    
    ItemDelegate::ItemDelegate(QObject *parent):QItemDelegate(parent)
    {
    ItemDelegate::ItemDelegate(QObject *parent):QItemDelegate(parent)
    {
         m_boutton = new QPushButton;
         m_boutton->setProperty("IsDelegateButton",true);
         m_boutton->setToolTip("ok");
         m_boutton->setStyleSheet("QPushButton {border-radius:0px;background:transparent; border-image: url(:/image/image/size.png);}");
    }
    
    void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        //ItemDelegate::paint(painter, option, index);
        painter->save();
        painter->restore();
        if (index.column() == 4)
       {
            QStyleOptionButton styleButton;                   //设置参数
            styleButton.rect=option.rect;
            styleButton.state  = QStyle::State_Enabled;
            if (option.state & QStyle::State_Selected) {
                painter->fillRect(option.rect, option.palette.highlight());
            }
            QWidget *widget = m_boutton;
            widget->style()->drawControl(QStyle::CE_PushButton,&styleButton,painter,widget);
        }
        else
        {
            //否则调用默认委托
            QItemDelegate::paint(painter, option, index);
        }
    }
    
    bool ItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
    {
        if(event->type() == QEvent::MouseButtonDblClick)     //禁止双击编辑
        {
                return true;
        }
        return QItemDelegate::editorEvent(event,model,option,index);
    }
    }
    
    void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        if (index.column() == 5&&index.row() == 1)
       {
            //按钮的风格选项
            //获取项风格设置
            QString value = index.model()->data(index, Qt::DisplayRole).toString();
            QStyleOptionComboBox comboBoxOption;
            comboBoxOption.rect=option.rect;
            comboBoxOption.state = option.state;
            comboBoxOption.state |= QStyle::State_Selected;
            comboBoxOption.editable = false;
            comboBoxOption.currentText=value;
           //绘制QCheckBox
           QApplication::style()->drawComplexControl(QStyle::CC_ComboBox,&comboBoxOption,painter);
           QApplication::style()->drawControl(QStyle::CE_ComboBoxLabel, &comboBoxOption, painter);
        }
       else
       {
           //否则调用默认委托
           QItemDelegate::paint(painter, option, index);
        }
    }
    
    QWidget *ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        Q_UNUSED(option)
        if (index.column() == 5&&index.row() == 1)//需要分类,这个cell为下拉框,不是的话为编辑框,这里没写编辑框。
        {
            QComboBox *editor = new QComboBox(parent);
            editor->addItem("q",0);
            editor->addItem("w",1);
            editor->setCurrentIndex(0);
            return editor;
        }
        return QItemDelegate::createEditor(parent, option, index);
    }
    
    void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
    {
        if (!(index.column() == 5&&index.row() == 1))return;
        QComboBox *currentComboBox = static_cast<QComboBox*>(editor);
        QString value = index.model()->data(index, Qt::DisplayRole).toString();
        int data = index.model()->data(index, Qt::UserRole + 1).toInt();
    
        qDebug()<<"text="<<value<<",data="<<data;
    
        int idx = currentComboBox->findData(data);
        if (idx > -1 ) {
            currentComboBox->setCurrentIndex(idx);
        }
    }
    
    void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
    {
        QComboBox *currentComboBox = static_cast<QComboBox*>(editor);
        QString displayData = currentComboBox->currentText();
        QVariant value = currentComboBox->currentData();
        model->setData(index, displayData, Qt::DisplayRole);
        model->setData( index, value, Qt::UserRole + 1 );
    }
    
    void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        editor->setGeometry(option.rect);
    }
    
    

    双击事件

       connect(ui->tableView,&QTableView::doubleClicked,this,[](const QModelIndex &index){
           if(index.isValid())
           {
             qDebug()<<index.model()->data(index, Qt::DisplayRole).toString();
           }
       });
    

    鼠标进入单元格事件

       connect(ui->tableView,&QTableView::entered,this,[=](const QModelIndex &index){
           if(index.isValid())
           {
             qDebug()<<index.model()->data(index, Qt::DisplayRole).toString();
             itemModel->item(index.row(),index.column())->setBackground(QBrush(QColor(255, 0, 0)));
           }
       });
    

    相关文章

      网友评论

        本文标题:QT QTableview QItemDelegate 简单使用

        本文链接:https://www.haomeiwen.com/subject/xclbiltx.html