最近使用qt写程序用到了treewidget和tablewidget
涉及到编辑默认情况下可以设置treewidget和tablewidget的item可编辑属性来进行编辑
默认情况只是简单的文本输入格式
在qt的demo中看到了spin box delegate实例
想到了使用delegate 委托
该实例只是对整个tablewidget使用同一个spin box格式的delegata
那么对于不同的列时候不通格式的委托那?
在
- QWidget *EventsDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem & option ,
- const QModelIndex & index ) const
- {
- if(index.column() == 0)
- {
- QComboBox *editor;
- editor = new QComboBox(parent);
- }else if(index.column() == 1)
- {
- QSpinBox *editor;
- editor = new QSpinBox(parent);
- }
- return editor;
- }
这样就可以通过判断不同的列使用不同的委托,当然对于不同的行,或者是特定的某一行某一列使用的委托都可以控制
进一步的想法就是实现一行中不同列的级联
类似php或者其他语言中中经常用到的
思路起始很清晰,两个列都是使用QComboBox,只是如何在同一行的前一列选中后,根据选中的数据初始化后一列的数据选项
起始说白了就是如何获取前一列的数据了
上网搜索了好长时间,从中有所启示
最后找到了这个函数
index.model()->index(index.row(),index.column() -1);
所以最后的代码就是:
- QWidget *EventsDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem & option ,
- const QModelIndex & index ) const
- QComboBox *editor;
- editor = new QComboBox(parent);
- if(index.column() == 0)
- {
- //控件列
- //初始化下拉框数据
- ..........
- }else if(index.column() == 1)
- {
- //获取同一行前一列的数据,根据数据指定该index的数据
- QModelIndex brothModelIndex = index.model()->index(index.row(),index.column() -1);
- QString str = brothModelIndex.data().toString();
- //根据str初始化本列的下拉框数据项
- .........
- }