[Interest] Most direct path to using a QComboBox to edit a cell in a QTableView?

Tony Rietwyk tony at rightsoft.com.au
Tue Jun 26 18:28:55 CEST 2012


Hi Frank, 

I haven't used QItemEditorFactory.  My reading of the docs suggests this
only applies if all of your strings are to be edited via the same combo.
None of the interfaces include a QModelIndex, so logically it can't be used
to provide different editors for different columns.  

I think that means you will need to provide a QStyledItemDelegate override.
For a given view, you can use just one item delegate for all non-standard
columns, or have separate delegates for different columns (or rows).  I
suggest that you load up the strings from the database only once, and store
them in the delegate.  Then you override createEditor to create the combo
box, and add the pre-loaded items.  

Note that delegates don't have to be specific to a particular view.  Here is
one that I use whenever I have a column of ints with a range: 

class TSpinBoxDelegate : public QStyledItemDelegate
{
	Q_OBJECT

private:
	int		minValue;
	int		maxValue;

public:
	TSpinBoxDelegate(int min,  int max,  QObject *parent = 0);

	QWidget *createEditor(
		QWidget *parent,
		const QStyleOptionViewItem &option,
		const QModelIndex &index) const;
};

................

TSpinBoxDelegate::TSpinBoxDelegate(int min,  int max,  QObject *parent) :
QStyledItemDelegate(parent)
{
	minValue = min;
	maxValue = max;
}


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

	QSpinBox *editor = new QSpinBox(parent);
	editor->setMinimum( minValue );
	editor->setMaximum( maxValue );
	return editor;
}

Hope that helps, 

Tony.





More information about the Interest mailing list