QTableView 一个单元格中添加按钮

时间:2021-11-21 10:32:13

首先谢谢 

http://www.cnblogs.com/li-peng/p/3961843.html

http://www.cnblogs.com/li-peng/p/4029885.html

http://qimo601.iteye.com/blog/1539147

QTableView 一个单元格中添加按钮QTableView 一个单元格中添加按钮

下面直接上代码:

E:\delcode\TowButtons\TowButtons.pro  在本电脑上面的路径

buttondelegate.h :

#ifndef BUTTONDELEGATE_H
#define BUTTONDELEGATE_H

#include <QItemDelegate>

class ButtonDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit ButtonDelegate(QObject *parent = 0);
void setBtnCnt(int btnCnt) {m_btnCnt=btnCnt;}
void createStyleOptionButton(QVector<QStyleOptionButton *> &vecBtns, QStringList & strtext) const;

void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) Q_DECL_OVERRIDE;

signals:

public slots:

private:
void showMsg(QString str);
int m_btnCnt;

private:

typedef QMap<QModelIndex, QPair<QStyleOptionButton*, QStyleOptionButton*>* > collButtons;
// collButtons m_btns;

typedef QMap<QModelIndex, QVector<QStyleOptionButton*> > vecButtons;
vecButtons m_VecBtns;
};

#endif // BUTTONDELEGATE_H

mainwindow.h :
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
class MainWindow : public QWidget
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();


};
#endif // MAINWINDOW_H

tablemodel.h:
#ifndef TABLEMODEL_H
#define TABLEMODEL_H

#include <QAbstractTableModel>

class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit TableModel(QObject *parent = 0);

int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
int columnCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE;

void setData(const QVector<QStringList>& data) ;
QVector<QStringList>& DataVector() {return m_data;}
void setHorizontalHeader(const QStringList& headers);
~TableModel(void);

signals:

public slots:


private:
QStringList m_HorizontalHeader;
QVector<QStringList> m_data;
};

#endif // TABLEMODEL_H

tableview.h:
#ifndef TABLEVIEW_H
#define TABLEVIEW_H

#include <QTableView>
#include "tablemodel.h"
#include "buttondelegate.h"

class TableView : public QTableView
{
Q_OBJECT
public:
explicit TableView(QWidget *parent = 0);
TableModel* tableModel() {return m_model;}

~TableView();

signals:

public slots:

private:
void iniData();

private:
TableModel *m_model;
ButtonDelegate *m_buttonDelegate;

};

#endif // TABLEVIEW_H
buttondelegate.cpp:
#include "buttondelegate.h"

#include <QApplication>
#include <QMouseEvent>
#include <QMessageBox>
#include <QPainter>
#include <QStyleOption>
#include <QDesktopWidget>
#include <QDebug>

ButtonDelegate::ButtonDelegate(QObject *parent) :
QItemDelegate(parent)
{
m_btnCnt=3;//! 默认为3个按钮
}
void ButtonDelegate::createStyleOptionButton(QVector<QStyleOptionButton*> & vecBtns, QStringList &strtext) const
{
for(int i=0;i<strtext.count();i++)
{
QStyleOptionButton* pBtn = new QStyleOptionButton();
pBtn->text = strtext[i];
pBtn->state |= QStyle::State_Enabled;
vecBtns.append(pBtn);
}
}

void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QVector<QStyleOptionButton*> vecBtns=m_VecBtns.value(index);
if (0==vecBtns.count()) {
QStringList strtext;
if(m_btnCnt==1)
{
strtext<<tr("XXX");
}
if(m_btnCnt==2)
{
strtext<<tr("XXX")<<tr("YYY");
}
if(m_btnCnt==3)
{
strtext<<tr("XXX")<<tr("YYY")<<tr("ZZZ");
}
createStyleOptionButton(vecBtns, strtext);
(const_cast<ButtonDelegate *>(this))->m_VecBtns.insert(index, vecBtns);
}
int widLen=option.rect.width();
if(m_btnCnt==3)
{
vecBtns[0]->rect = option.rect.adjusted(0, 4, -(widLen*2/3 + 4) , -4);
vecBtns[1]->rect = option.rect.adjusted(widLen/3 + 4, 4, -(widLen/3+4), -4);
vecBtns[2]->rect = option.rect.adjusted(widLen*2/3 + 4 , 4, -4, -4);
}
if(m_btnCnt==2)
{
vecBtns[0]->rect = option.rect.adjusted(4, 4, -(widLen/2 + 4) , -4);
vecBtns[1]->rect = option.rect.adjusted(widLen/2 + 4, 4, -4, -4);
}
if(m_btnCnt==1)
{
vecBtns[0]->rect = option.rect.adjusted(0, 4, -4, -4);
}

painter->save();

if (option.state & QStyle::State_Selected) {
painter->fillRect(option.rect, option.palette.highlight());

}
painter->restore();
QApplication::style()->drawControl(QStyle::CE_PushButton, vecBtns[0], painter);
if(m_btnCnt>=2) QApplication::style()->drawControl(QStyle::CE_PushButton, vecBtns[1], painter);
if(m_btnCnt==3)QApplication::style()->drawControl(QStyle::CE_PushButton, vecBtns[2], painter);
}

bool ButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
if (event->type() == QEvent::MouseButtonPress) {

QMouseEvent* e =(QMouseEvent*)event;

if (m_VecBtns.contains(index)) {
QVector<QStyleOptionButton*> btns = m_VecBtns.value(index);
if (btns[0]->rect.contains(e->x(), e->y())) {
btns[0]->state |= QStyle::State_Sunken;
}
else if(btns[1]->rect.contains(e->x(), e->y())) {
btns[1]->state |= QStyle::State_Sunken;
}
else if(btns[2]->rect.contains(e->x(), e->y())) {
btns[2]->state |= QStyle::State_Sunken;
}
}
}
if (event->type() == QEvent::MouseButtonRelease) {
QMouseEvent* e =(QMouseEvent*)event;

if (m_VecBtns.contains(index)) {
QVector<QStyleOptionButton*> btns = m_VecBtns.value(index);
if (btns[0]->rect.contains(e->x(), e->y())) {
btns[0]->state &= (~QStyle::State_Sunken);
showMsg(tr("btn1 column %1").arg(index.column()));
} else if(btns[1]->rect.contains(e->x(), e->y())) {
btns[1]->state &= (~QStyle::State_Sunken);
showMsg(tr("btn2 row %1").arg(index.row()));
}
else if(btns[2]->rect.contains(e->x(), e->y())) {
btns[2]->state &= (~QStyle::State_Sunken);
showMsg(tr("btn2 row %1").arg(index.row()));
}
}
}
return true;
}

void ButtonDelegate::showMsg(QString str)
{
QMessageBox msg;
msg.setText(str);
msg.exec();
}

main.cpp:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}
mainwindow.cpp:
#include "mainwindow.h"
#include "tableview.h"
#include "tablemodel.h"
#include <QLayout>
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)

{
this->resize(800, 600);
TableView *tv = new TableView(this);
QVBoxLayout* layout = new QVBoxLayout();

layout->addWidget(tv);
this->setLayout(layout);
}

MainWindow::~MainWindow()
{

}
tablemodel.cpp:
#include "tablemodel.h"

TableModel::TableModel(QObject *parent) :
QAbstractTableModel(parent)
{
}

TableModel::~TableModel()
{

}


int TableModel::rowCount(const QModelIndex &parent) const
{
int i=m_data.size();
return i;
}

int TableModel::columnCount(const QModelIndex &parent) const
{
int j=m_HorizontalHeader.count();
return j;
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole) {
int ncol = index.column();
int nrow = index.row();
QStringList values = m_data.at(nrow);
if (values.size() > ncol)
return values.at(ncol);
else
return QVariant();
}
return QVariant();
}

Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;

Qt::ItemFlags flag = QAbstractItemModel::flags(index);

// flag|=Qt::ItemIsEditable // 设置单元格可编辑,此处注释,单元格无法被编辑
return flag;
}

void TableModel::setHorizontalHeader(const QStringList &headers)
{
m_HorizontalHeader = headers;
}


QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
return m_HorizontalHeader.at(section);
}
return QAbstractTableModel::headerData(section, orientation, role);
}

void TableModel::setData(const QVector<QStringList> &data)
{
m_data = data;
}
tableview.cpp:
#include "tableview.h"

#include "tablemodel.h"
#include "buttondelegate.h"
#include <QHeaderView>

TableView::TableView(QWidget *parent) :
QTableView(parent)
{
iniData();
}

TableView::~TableView()
{
delete m_model;
}

void TableView::iniData()
{
m_model = new TableModel();
this->setModel(m_model);
QStringList headers;
headers << "Id" << "Progress"<< "Progress-test";
m_model->setHorizontalHeader(headers);

QVector<QStringList> data;
data.append(QStringList() << "1" << "01"<< "Progress-test111");
data.append(QStringList() << "2" << "02"<< "Progress-test222");
data.append(QStringList() << "3" << "03"<< "Progress-test333");
data.append(QStringList() << "4" << "04"<< "Progress-test444");
data.append(QStringList() << "5" << "05"<< "Progress-test555");
m_model->setData(data);

m_buttonDelegate = new ButtonDelegate(this);
m_buttonDelegate->setBtnCnt(3);
// this->setItemDelegateForRow(1, m_buttonDelegate);
this->setItemDelegateForColumn(1, m_buttonDelegate);
emit m_model->layoutChanged();
this->setColumnWidth(1, 500);
this->horizontalHeader()->setStretchLastSection(true);
}

下面是QTABLEVIEW的一行中添加RADIO的例子:

QTableView 一个单元格中添加按钮

下面是代码:

delegate_ItemRbtn_RadioBtn.h:

#ifndef delegate_ItemRbtn_RadioBtn_H
#define delegate_ItemRbtn_RadioBtn_H

#include <QApplication>
#include <QMouseEvent>
#include <QMessageBox>
#include <QPainter>
#include <QStyleOption>
#include <QDesktopWidget>
#include <QTableView>
#include <QDebug>
#include <QItemDelegate>
#include <QObject>

class QStrforRadioShowData: public QObject
{
    Q_OBJECT
public:
    explicit QStrforRadioShowData(QObject *parent = 0);
    ~QStrforRadioShowData(void);
    QString strcheck;
    QString struncheck;
};

class RadioDelegateisOut : public QItemDelegate
{
    Q_OBJECT
public:
    explicit RadioDelegateisOut(QObject *parent = 0);
    void createStyleOptionButton(QStyleOptionButton *&vecBtns, QString &strtext) const;

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) Q_DECL_OVERRIDE;

private:
    QStrforRadioShowData strData;
public:
    typedef QMap<QModelIndex, QStyleOptionButton* >  vecButtons;
    vecButtons m_VecBtns;
    QVector<QString> m_RadioUserSel;
};
#endif // BUTTONDELEGATE_H

tablemodel_ItemRbtn_isOut.h:

#ifndef TABLEMODEL_ISOUT_H
#define TABLEMODEL_ISOUT_H

#include <QAbstractTableModel>
//#include "../PublicDataType.h"
//#include "../PublicQStr.h"

struct PExmlNeedData
{
    QString strCol1Data;
    QStringList strCol2Data;
};

class ItemRbtnisOutModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    explicit ItemRbtnisOutModel(QObject *parent = 0);
    ~ItemRbtnisOutModel(void);

    int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
    int columnCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
    QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
    Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE;
    //Q_INVOKABLE virtual bool setTotalData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);

public:
    //void setShowTotalData(QVector<sHorizontalHeader> &data) ;
    void setShowData(QVector<PExmlNeedData> &invalue, QVector<QString> &vecckUserValue, QVector<QString> &vecRadioUserValue);
    //QVector<sHorizontalHeader>& DataVector() {return m_SMSDTableModelTotalData;}
    void setHorizontalHeader(const QStringList &headers);

    QVariant getColData(QString strColTitle, PExmlNeedData &XMLlineData)const;
    int FindValueCol(QString invalue)const;
public:
    QStringList m_HorizontalHeader;//! 水平头的数据显示 根据SMSDTableViewColSet.xml中的文件依次排列的数据
    //QVector<sHorizontalHeader> m_SMSDTableModelTotalData;//! 所有的整体数据
    QVector<PExmlNeedData>  m_AllVecData;//! 根据读取的整体数据结合要显示的哪些列所存储的显示数据
    QVector<QStringList> myBtnProces;
    QVector<QString> m_vecckUserValue;
    QVector<QString> m_vecRadioUserValue;
    int ckCol;
    int RadioCol;
};

#endif


delegate_ItemRbtn_RadioBtn.cpp:

#include "delegate_ItemRbtn_RadioBtn.h"


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

void RadioDelegateisOut::createStyleOptionButton(QStyleOptionButton* &  vecBtns, QString &strtext) const
{    
    QStyleOptionButton* pBtn = new QStyleOptionButton();
    pBtn->text = strtext;
    pBtn->state |= QStyle::State_Enabled;
    vecBtns=pBtn;
}

void RadioDelegateisOut::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionButton*  vecBtns=m_VecBtns.value(index);
       if (NULL==vecBtns)
       {
           QString strtext;
           strtext=strData.struncheck;
           createStyleOptionButton(vecBtns, strtext);
           (const_cast<RadioDelegateisOut *>(this))->m_VecBtns.insert(index, vecBtns);
       }
       int widLen=option.rect.width();
       vecBtns->rect = option.rect.adjusted(0, 4, -4, -4);

       painter->save();

       if (option.state & QStyle::State_Selected) {
           painter->fillRect(option.rect, option.palette.highlight());
       }
       painter->restore();//忘了加此句,出现CONSOLE:QPainter::end: Painter ended with 2 saved states
       QApplication::style()->drawControl(QStyle::CE_RadioButton, vecBtns, painter);
}

bool RadioDelegateisOut::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    int r=index.row();
    int c=index.column();
    //Q_UNUSED( option)
    //Q_UNUSED( model)
    if (event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent* e =(QMouseEvent*)event;

        if (m_VecBtns.contains(index))
        {
            QStyleOptionButton* btns = m_VecBtns.value(index);
            if (btns->rect.contains(e->x(), e->y()))
            {
                QStyle::State sold = btns->state;
                QStyle::State sisOn = sold&(0x000000f0);
				if(sisOn==QStyle::State_None)
                {
                    btns->state|=QStyle::State_On;
                    btns->text="checked";
                }
				if(sisOn==QStyle::State_On)
                {
                    btns->state&=(~QStyle::State_On);
                    btns->text="unchecked";
                    //! 取消勾选
                }
                m_RadioUserSel[r]=btns->text;
            }
        }
    }
    model->setData(index, m_RadioUserSel[r], Qt::CheckStateRole);

    return true;
}

QStrforRadioShowData::QStrforRadioShowData(QObject *parent)
{
    strcheck=tr("checked");
    struncheck=tr("unchecked");
}

QStrforRadioShowData::~QStrforRadioShowData()
{

}

tablemodel_ItemRbtn_isOut.cpp:

#include "tablemodel_ItemRbtn_isOut.h"

ItemRbtnisOutModel::ItemRbtnisOutModel(QObject *parent) :
    QAbstractTableModel(parent)
{
    //m_vecckUserValue.clear();
}

ItemRbtnisOutModel::~ItemRbtnisOutModel()
{

}


int ItemRbtnisOutModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED( parent)
    int i=m_AllVecData.size();
    return i;
}

int ItemRbtnisOutModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED( parent)
    int j=m_HorizontalHeader.size();
    return j;
}
QVariant ItemRbtnisOutModel::getColData(QString strColTitle,PExmlNeedData &XMLlineData)const
{
    //headers<<QString("parameterName")<<QString("parameterType")<<QString("Out-process-select");
    if(strColTitle==tr("parameterName"))
        return XMLlineData.strCol1Data;
//    if(strColTitle==tr("parameterType"))
//        return XMLlineData.argTypeType;
//    if(strColTitle==tr("Value"))
//        return XMLlineData.default_value;
//    if(strColTitle==tr("valueRange"))
//        return XMLlineData.valueRange;
//    if(strColTitle==tr("valueUnit"))
//        return XMLlineData.valueUnit;
//    if(strColTitle==tr("desc"))
//        return XMLlineData.desc;
//    if(strColTitle==tr("paramIndex"))
//        return QString(tr("%1")).arg(XMLlineData.paramIndex);
    if(strColTitle==tr("Out-process-select"))//1、文件 2、数据库 3、推送
    {
        QStringList ll=XMLlineData.strCol2Data;
//        ll.append(QLJTSTR::CHECK_FILE);
//        ll.append(QLJTSTR::CHECK_DATABASE);
//        ll.append(QLJTSTR::CHECK_PUSH);
        return ll;
    }
        //return QString(tr("%1%2%3")).arg(CHECK_FILE).arg(CHECK_DATABASE).arg(CHECK_PUSH);
    return "";
}

int ItemRbtnisOutModel::FindValueCol(QString invalue) const
{
    for(int i=0;i<m_HorizontalHeader.size();i++)
    {
        QString str = m_HorizontalHeader.at(i);
        if(invalue==str)
            return i;
    }
    return -1;
}

QVariant ItemRbtnisOutModel::data(const QModelIndex &index, int role) const
{
    //qDebug()<<"ItemRbtnisOutModel::data-role"<<role;
    if (!index.isValid())
        return QVariant();
    int nrow =  index.row();
    int ncol = index.column();
    PExmlNeedData XMLlineData = m_AllVecData.at(nrow);
    QString strColTitle = m_HorizontalHeader.at(ncol);
    if (role == Qt::DisplayRole)
    {       
        QVariant strValue = this->getColData(strColTitle,XMLlineData);
        //qDebug()<<"ItemRbtnisOutModel::data"<<nrow<<ncol<<role<<strValue;
        return strValue;
    }
    if (role == Qt::CheckStateRole&&ncol==ckCol)
    {
        QString sList = m_vecckUserValue.at(nrow);
        //qDebug()<<"ItemRbtnisOutModel::data"<<nrow<<ncol<<role<<sList;
        return sList;
    }
    if (role == Qt::CheckStateRole&&ncol==RadioCol)
    {
        QString sList = m_vecRadioUserValue.at(nrow);
        //qDebug()<<"ItemRbtnisOutModel::data"<<nrow<<ncol<<role<<sList;
        return sList;
    }
    return QVariant();
}

bool ItemRbtnisOutModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
        int row = index.row();
        int col=index.column();
        if (index.isValid() && role == Qt::CheckStateRole &&col==ckCol)
        {
            QString strnow = value.toString();
            m_vecckUserValue[row]=strnow;
            //qDebug()<<"tableArrorRbtnModel::setData"<<strnow;
            emit dataChanged(index, index);
            return true;
        }
        if (index.isValid() && role == Qt::CheckStateRole &&col==RadioCol)
        {
            QString strnow = value.toString();
            m_vecRadioUserValue[row]=strnow;
            //qDebug()<<"tableArrorRbtnModel::setData"<<strnow;
            emit dataChanged(index, index);
            return true;
        }
        return false;
}

Qt::ItemFlags ItemRbtnisOutModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    Qt::ItemFlags flags = QAbstractItemModel::flags(index);

    int col = index.column();
    if(col==ckCol)
        flags |= Qt::ItemIsEditable;
    if(col==RadioCol)
        flags |= Qt::ItemIsEditable;

    return flags;
}

void ItemRbtnisOutModel::setHorizontalHeader(const QStringList& headers)
{
    m_HorizontalHeader =  headers;
    ckCol=FindValueCol(tr("Out-process-select"));
    RadioCol=FindValueCol(tr("isActive"));
}


QVariant ItemRbtnisOutModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    int m=m_HorizontalHeader.size();
    if(m==0) return QVariant();
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
        QString strTemp=m_HorizontalHeader.at(section);
        //QString strTemp=QString::fromLocal8Bit(ss.c_str());
        //QString strTemp=QString::fromStdString(ss.c_str());
        //QString strTemp(ss.c_str());
        //QVariant vaTemp(strTemp);
        return strTemp;
    }
    return QAbstractTableModel::headerData(section, orientation, role);
}

void ItemRbtnisOutModel::setShowData(QVector<PExmlNeedData> &invalue,QVector<QString> &vecckUserValue,QVector<QString> &vecRadioUserValue)
{
    m_AllVecData.clear();
    m_AllVecData=invalue;

    m_vecckUserValue.clear();
    m_vecckUserValue=vecckUserValue;

    m_vecRadioUserValue.clear();
    m_vecRadioUserValue=vecRadioUserValue;
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "delegate_ItemRbtn_RadioBtn.h"
#include "tablemodel_ItemRbtn_isOut.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void initTabView(QVector<PExmlNeedData> &invalue, QVector<QString> &vecRadioUserValue);
public slots:
    void getRadioValue();
private:
    Ui::MainWindow *ui;

    ItemRbtnisOutModel *m_isOutmodel;
    RadioDelegateisOut *m_isOutDelegate;
};


#endif // MAINWINDOW_H

mainwindow.cpp:

 
#include "mainwindow.h"
#include <QTranslator>
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    QVector<PExmlNeedData> invalue;

    PExmlNeedData r0;
    r0.strCol1Data="strCol1Data";
    r0.strCol2Data<<"strCol2Data--000"<<"strCol2Data--011"<<"strCol2Data--022";

    PExmlNeedData r1;
    r1.strCol1Data="strCol1Data";
    r1.strCol2Data<<"strCol2Data--100"<<"strCol2Data--111"<<"strCol2Data--122";

    invalue.push_back(r0);invalue.push_back(r1);

    QVector<QString> vecRadioUserValue;
    QString s0;s0="unchecked";
    QString s1;s1="unchecked";
    vecRadioUserValue.push_back(s0);
    vecRadioUserValue.push_back(s1);

    initTabView(invalue,vecRadioUserValue);
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(getRadioValue()));
}

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

void MainWindow::initTabView(QVector<PExmlNeedData> &invalue,QVector<QString> &vecRadioUserValue)
{
    m_isOutmodel = new ItemRbtnisOutModel(this);
    QStringList headers;
    headers<<QString(tr("parameterName"))<<QString(tr("Out-process-select"))<<QString(tr("isActive"));
    m_isOutmodel->setHorizontalHeader(headers);

    m_isOutmodel->setShowData(invalue,vecRadioUserValue,vecRadioUserValue);

    ui->tableView_isOut->setSelectionBehavior(QAbstractItemView::SelectRows);
    //m_pageRes.tableView_isOut->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView_isOut->setSelectionMode(QTableView::SingleSelection);
    //m_pageRes.tableView_isConf->setColumnWidth(colIndex+ipsCnt, 50);
    ui->tableView_isOut->horizontalHeader()->setStretchLastSection(true);
    ui->tableView_isOut->setModel(m_isOutmodel);
    int allColCnt = headers.size();

    m_isOutDelegate = new RadioDelegateisOut(this);
    m_isOutDelegate->m_RadioUserSel=vecRadioUserValue;
    ui->tableView_isOut->setItemDelegateForColumn(allColCnt-1, m_isOutDelegate);
}

void MainWindow::getRadioValue()
{
    QVector<QString> getRadioSel=m_isOutmodel->m_vecRadioUserValue;
    qDebug()<<"getRadioSel"<<getRadioSel;
}

main.cpp:
 
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
//    LangSwitch w;
//    w.show();

    return a.exec();
}
最后忘了添加更新EDITOR的代码了,下面只写出CPP代码:
 
void RadioDelegateisOut::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}



下面是一种延伸方法:
 
 
 
form.h
#ifndef FORM_H
#define FORM_H

#include <QWidget>
#include <QDebug>

namespace Ui {
class Form;
}

class Form : public QWidget
{
    Q_OBJECT

public:
    explicit Form(QWidget *parent = 0);
    ~Form();
    QString current_PushedBtn();
    void setEverBtnText(int i ,QString s);
    void setCurrent_PushedBtnStr(QString s);
private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();
private:
    Ui::Form *ui;
    QString mycurrent_btnPsh;
    int  mycurrent_btnPushedindex;

Q_SIGNALS:
    void sig_btnPsh(int btnIndex);
};

#endif // FORM_H
form.cpp
#include "form.h"
#include "ui_form.h"

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

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

QString Form::current_PushedBtn()
{
    return mycurrent_btnPsh;
}

void Form::setCurrent_PushedBtnStr(QString s)
{
    mycurrent_btnPsh=s;
}

void Form::setEverBtnText(int i, QString s)
{
    if(i==0) ui->pushButton->setText(s);
    else if(i==1) ui->pushButton_2->setText(s);
    else if(i==2) ui->pushButton_3->setText(s);
    else ui->pushButton->setText(s);
}

void Form::on_pushButton_clicked()
{
    mycurrent_btnPushedindex=0;
    emit sig_btnPsh(0);
}

void Form::on_pushButton_2_clicked()
{
    mycurrent_btnPushedindex=1;
    emit sig_btnPsh(1);
    //QPushButton * pb = qobject_cast<QPushButton *>(sender());
    //qDebug()<<pb->text();
}

void Form::on_pushButton_3_clicked()
{
    mycurrent_btnPushedindex=2;
    emit sig_btnPsh(2);
}

imagedelegate.h
#ifndef IMAGEDELEGATE_H
#define IMAGEDELEGATE_H

#include <QItemDelegate>
#include "form.h"

class ImageDelegate : public QItemDelegate
{
    Q_OBJECT

public:
    ImageDelegate(QObject *parent = 0);

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget *editor, QAbstractItemModel *model,
                      const QModelIndex &index) const Q_DECL_OVERRIDE;
private slots:
    void slot_emitCommitData(int btnIndex);
private:
    int curPushedBtnIndex;
};
#endif

imagedelegate.cpp
#include <QtWidgets>

#include "imagedelegate.h"

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

QWidget *ImageDelegate::createEditor(QWidget *parent,
                                     const QStyleOptionViewItem & /* option */,
                                     const QModelIndex &index) const
{
    Form *f = new Form(parent);
    if (index.column() == 1)
    {}
    else if (index.column() == 2)
    {}

    connect(f, SIGNAL(sig_btnPsh(int)), this, SLOT(slot_emitCommitData(int)));
    return f;
}

void ImageDelegate::setEditorData(QWidget *editor,
                                  const QModelIndex &index) const
{
    Form *f = qobject_cast<Form *>(editor);
    if (!f)
        return;
    QString btnrc = f->current_PushedBtn();
    btnrc = QString("%1 %2")
            .arg(btnrc).arg(curPushedBtnIndex);
   // QString ss = QString("tt %1").arg(btnindex);
    f->setEverBtnText(curPushedBtnIndex, btnrc);
}

void ImageDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
    Form *f = qobject_cast<Form *>(editor);
    if (!f)
        return;

    int r=index.row();
    int c=index.column();

    QString status = QString("%1 %2")
            .arg(r).arg(c);
    f->setCurrent_PushedBtnStr(status);
    status = QString("%1 %2")
            .arg(status).arg(curPushedBtnIndex);
    model->setData(index, status);
}

void ImageDelegate::slot_emitCommitData(int btnIndex)
{
    curPushedBtnIndex=btnIndex;
    emit commitData(qobject_cast<QWidget *>(sender()));
}


mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "form.h"
#include <QTableWidgetItem>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void createContextMenu();
    void createActions();
    QAction *addImagesAct;
    QAction *removeAllImagesAct;

    void addImages();
public slots:
    void changeIcon(QTableWidgetItem *item );
    void addImagesSlot();
    void removeAllImages();
private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStringList>
#include <QFileDialog>
#include "imagedelegate.h"
#include <QDebug>

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

    ui->imagesTable->setSelectionMode(QAbstractItemView::NoSelection);
    QStringList labels;
    labels << tr("Image") << tr("Mode") << tr("State");
    ui->imagesTable->setColumnCount(3);
    ui->imagesTable->setHorizontalHeaderLabels(labels);
    ui->imagesTable->verticalHeader()->hide();

    //ui->imagesTable->horizontalHeader()->setDefaultSectionSize(90);
//    ui->imagesTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
//    ui->imagesTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
//    ui->imagesTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);

    ui->imagesTable->setSelectionMode(QAbstractItemView::NoSelection);
    ui->imagesTable->setItemDelegate(new ImageDelegate(this));

    addImages();
    createActions();
    createContextMenu();

    connect(ui->imagesTable, SIGNAL(itemChanged(QTableWidgetItem*)),this, SLOT(changeIcon(QTableWidgetItem *)));
}

void MainWindow::changeIcon(QTableWidgetItem *item)
{
    qDebug()<<"MainWindow::changeIcon()";
//    int r = item->row();
//    int c = item->column();

//    int row=0;
//    if(c==1 || c==2)
//    {
//        QTableWidgetItem *itemx = ui->imagesTable->item(row, c);
//        QModelIndex mi = ui->imagesTable->indexFromItem(itemx) ;
//        ImageDelegate  *id =  qobject_cast<ImageDelegate *>(ui->imagesTable->itemDelegate(mi)) ;
//        bool B = id->isWidgetType();
//        int tt=98;
//    }
//    for (int row = 0; row < ui->imagesTable->rowCount(); ++row)
//    {
//        QTableWidgetItem *item0 = ui->imagesTable->item(row, 0);
//        QTableWidgetItem *item1 = ui->imagesTable->item(row, 1);
//        QTableWidgetItem *item2 = ui->imagesTable->item(row, 2);
//        //qDebug()<<"row="<<row<<item0->checkState()<<item1->text()<<item2->text();
//    }
}

void MainWindow::addImages()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(this,
                                    tr("Open Images"), "",
                                    tr("Images (*.png *.xpm *.jpg);;"
                                       "All Files (*)"));
    if (!fileNames.isEmpty()) {
        foreach (QString fileName, fileNames)
        {
            int row = ui->imagesTable->rowCount();
            ui->imagesTable->setRowCount(row + 1);
            QString imageName = QFileInfo(fileName).baseName();
            QTableWidgetItem *item0 = new QTableWidgetItem(imageName);
            item0->setData(Qt::UserRole, fileName);
            item0->setFlags(item0->flags() & ~Qt::ItemIsEditable);
            QTableWidgetItem *item1 = new QTableWidgetItem();
            QTableWidgetItem *item2 = new QTableWidgetItem();
            //QTableWidgetItem *item1 = new QTableWidgetItem(tr("Normal"));
            //QTableWidgetItem *item2 = new QTableWidgetItem(tr("Off"));

            ui->imagesTable->setItem(row, 0, item0);
            ui->imagesTable->setItem(row, 1, item1);
            ui->imagesTable->setItem(row, 2, item2);
            ui->imagesTable->openPersistentEditor(item1);
            ui->imagesTable->openPersistentEditor(item2);

            item0->setCheckState(Qt::Checked);
        }
    }
}

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

void MainWindow::createActions()
{
    addImagesAct = new QAction(tr("&Add Images..."), this);
    addImagesAct->setShortcut(tr("Ctrl+A"));
    connect(addImagesAct, SIGNAL(triggered()), this, SLOT(addImagesSlot()));

    removeAllImagesAct = new QAction(tr("&Remove All Images"), this);
    removeAllImagesAct->setShortcut(tr("Ctrl+R"));
    connect(removeAllImagesAct, SIGNAL(triggered()),
            this, SLOT(removeAllImages()));
}

void MainWindow::createContextMenu()
{
    ui->imagesTable->setContextMenuPolicy(Qt::ActionsContextMenu);
    ui->imagesTable->addAction(addImagesAct);
    ui->imagesTable->addAction(removeAllImagesAct);
}

void MainWindow::addImagesSlot()
{
    qDebug()<<"addImagesSlot()";
}

void MainWindow::removeAllImages()
{
    qDebug()<<"removeAllImages()";
}

void MainWindow::on_pushButton_clicked()
{
    addImages();
}

main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}


QTableView 一个单元格中添加按钮
要把form.ui 里面的控件在界面上设置一下,让它们彼此紧密的相连,因为这个是在form.ui 里面*拉的控件,所以如果你需要哪些控件,可以在上面自己随便拖放,按照需求进行你想要的功能,所以是可扩展的。