本文介绍了将自定义窗口小部件添加到QTableWidget单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有使用qt designer制作的自定义小部件,我想将其添加到QTableWidget单元格中.但这不起作用.
I have custom widget made with qt designer and i want to add it to QTableWidget cell.But it doesn't work.
这是代码:
int nRows =10;
for(int row = 0; row < nRows;row++;)
{
QTableWidgetItem* item = new QTableWidgetItem();
CustomWdg* wdg=new CustomWdg( );
mTableWdg->insertRow( row );
mTableWdg->setItem(row, 0, item);
mTableWdg->setCellWidget( row, 0, wdg );
}
推荐答案
如果要将自定义窗口小部件添加到表单元格,则可以使用QItemDelegate.
If you want to add custom widget into table cell you can use QItemDelegate.
创建您自己的Delegate类,并从QItemDelegate继承它.
Create your own Delegate class and inherit it from QItemDelegate.
class MyDelegate : public QItemDelegate
{
public:
CChoicePathDelegate (QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; //delegate editor (your custom widget)
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const; //transfer editor data to model
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};
然后使用此方法自行设置Table的委托.
And then set delegate for Table with this methods on your own.
setItemDelegate(QAbstractItemDelegate *)
setItemDelegateForColumn(int, QAbstractItemDelegate *)
setItemDelegateForRow(int, QAbstractItemDelegate *)
我已经尝试过以下代码:
I have tried this code:
#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QHBoxLayout *l = new QHBoxLayout();
l->addWidget((new QPushButton("I`m in cell")));
l->addWidget((new QLabel("Test label")));
QWidget *w = new QWidget();
w->setLayout(l);
ui->tableWidget->setCellWidget(1,1, w);
}
Widget::~Widget()
{
delete ui;
}
结果是:
这篇关于将自定义窗口小部件添加到QTableWidget单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!