Qt QItemSelection::indexes() return is wrong - c++

I implemented a derived class from QAbstractItemModel, and it seems to work fine.
Then I created a QItemSelectionModel and assigned it to the mentioned QAbstractItemModel.
My QAbstractItemModel is not a widget and is not displayed, only manages a hierarchy.
When the selection is changed, and the QItemSelection model emits the selection changed signal the QItemSelections selected and deselected seem to contain the right data.
The problem arises when i call their ::indexes() function to get the indexes of the selected items, it returns no items, even so I know items are selected and the ::width() and ::height() functions return correct values.
Basic example code:
(A working example and files that demonstrates the problem follows)
class DerivedModel : public QAbstractItemModel {
DerivedModel(QObject* parent) : QAbstractItemModel(parent)
,m_selectionModel(nullptr)
{
//create the selection model and assign this model to it
m_selectionModel = new QItemSelectionModel(this, this);
}
...
//all needed overload functions
//the DerivedModel works great
...
private:
QItemSelectionModel* m_selectionModel;
}
//in a different object called SceneModel (a QGraphicsScene which shows graphical items based on the DerivedModel) which is connected to the selection models selectionChanged() signal I query the new selection
SceneModel::setSelectedItems(const QItemSelection& selected, const QItemSelection& deselected){
int selectionSize_A = selected.size(); //this returns correct number of selected items
int selectionSize_B = selected.indexes().size(); //this returns 0 -> WRONG
int selectionSize_C = selected.value(0).indexes().size(); //this returns 0 -> WRONG
int selectionSize_CA = selected.value(0).width(); //this returns correct
int selectionSize_CB = selected.value(0).height(); //this returns correct
//if I purposefully try to access the 1st selected index via QItemSelectionRange::topLeft() all is good and I get the index:
QItemSelectionRange range = selected.value(0);
QModelIndex topLeft = range.topLeft(); //cool, i get the 1st selected index
//it seems there is a problem with the ::indexes function, so dived into the Qt5 source and basically implemented again whats done there and it works.
}
A link to the files including cmake build:
https://drive.google.com/file/d/0Bz03DnXr46WXYXRCeExtaHZadUU/view?usp=sharing
Whats happening there:
A DerivedModel is created and holds 2 items (A and B) under root item (ROOT).
Pushing a button signals the QItemSelectionModel to select/deselect A or B.
If the item is found in the model "Found Item :)" is printed, showing the item exists and is available to the model.
The QGraphicsView holds a Scene (derived from QGraphicsScene).
That scene is empty, and only represents an object receiving the selectionChange signal from the selection model.
When it receives that signal it prints "Scene received item selection change" so we can see the signal has passed.
then comes the real stuff:
we get a count of how many QItemRanges are in the passed "selected" variable, which is correct.
we get a count of how many indexes are inside all the ranges in the passed "selected" variable (selected.indexes()) that returns 0 which is wrong as we can soon see
we manually access the 1st index in the 1st range in the "selected" variable (selected.value(0).topLeft()) and see that it indeed holds an index pointing to the right item, showing the problem.
If anybody knows about something, or can see an error in my approach please let me know.
Thanks!
Linux Manjaro Gcc 4.9.1 Qt5.3
DerivedModel.h:
#ifndef DERIVEDMODEL_H
#define DERIVEDMODEL_H
#include <QAbstractItemModel>
//fwd declaration
QT_FORWARD_DECLARE_CLASS(QItemSelectionModel)
class Item;
class DerivedModel : public QAbstractItemModel{
Q_OBJECT
public:
//model is a singleton, function to get instance
static DerivedModel& instance();
explicit DerivedModel(QObject* parent);
virtual ~DerivedModel();
/////////////////model overloads//////////////////////////////
QVariant data(const QModelIndex& index, int role) const;
Qt::ItemFlags flags(const QModelIndex& index) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex& index) const;
int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex& parent = QModelIndex()) const {Q_UNUSED(parent); return 1;}
//////////////////////////////////////////////////////////////
//get the item from an index
Item* item(const QModelIndex& index) const { return static_cast<Item*>(index.internalPointer());}
//get the index from an item name
const QModelIndex indexFromName(const QString& name);
//add an item
void addItem(const QString& name, Item* parent=nullptr);
//get the selection model
QItemSelectionModel* selectionModel() const {return m_selectionModel;}
private:
//the instance of the singleton to return
static DerivedModel* m_instance;
//the root object for the model
//never actually used
Item* m_rootItem;
//selection model for handeling selection
QItemSelectionModel* m_selectionModel;
};
#endif
DerivedModel.cpp
#include "DerivedModel.h"
#include "Item.h"
#include <QItemSelectionModel>
#include <QDebug>
//init static member
DerivedModel* DerivedModel::m_instance = nullptr;
DerivedModel& DerivedModel::instance(){
//check if set
if(!m_instance){
qDebug() << "ERROR model instance not set";
std::abort();
}
return *m_instance;
}
DerivedModel::DerivedModel(QObject* parent):
QAbstractItemModel(parent)
,m_rootItem(nullptr)
,m_selectionModel(nullptr)
{
//set the instance
m_instance = this;
//creae root item
m_rootItem = new Item("ROOT");
//init selection model
m_selectionModel = new QItemSelectionModel(this, this);
}
DerivedModel::~DerivedModel(){
//selection model is child so gets deleted
}
QVariant DerivedModel::data(const QModelIndex& index, int role) const {
//if the index is valid
if(!index.isValid()) {
qDebug() << "Index not valid!";
return QVariant();
}
//switch role
switch(role){
case Qt::DisplayRole:{
QString name = static_cast<Item*>(index.internalPointer())->name();
return name;
break;
}
default:
return QVariant();
}
}
Qt::ItemFlags DerivedModel::flags(const QModelIndex& index) const {
//check valid
if(!index.isValid()) return 0;
return static_cast<Item*>(index.internalPointer())->flags();
}
QVariant DerivedModel::headerData(int section, Qt::Orientation orientation, int role) const {
//unused for now
Q_UNUSED(section);
Q_UNUSED(orientation);
if(role==Qt::DisplayRole) return QVariant("HeaderData");
else return QVariant();
}
QModelIndex DerivedModel::index(int row, int column, const QModelIndex& parent) const {
Item* parentItem(nullptr);
//is valid?
if(!parent.isValid()) {
parentItem = m_rootItem;
}
else {
parentItem = item(parent);
}
//child pointer holder
Item* childItem = parentItem->children().value(row);
//is null?
if(childItem){
return createIndex(row, column, childItem);
}
else {
return QModelIndex();
}
}
QModelIndex DerivedModel::parent(const QModelIndex& index) const {
//check valid
if(!index.isValid()) return QModelIndex();
//get child
Item* childItem = static_cast<Item*>(index.internalPointer());
//find parent
Item* parentItem = childItem->parent();
//is null?
if(parentItem == m_rootItem) return QModelIndex();
return createIndex(parentItem->parent()->children().indexOf(parentItem), 0, parentItem);
}
int DerivedModel::rowCount(const QModelIndex& parent) const {
//parent holder
Item* parentItem;
//check 0 column (not sure why, but is in example, maybe the model iterates also through different columns)
if(parent.column()>0) return 0;
//check valid
if(!parent.isValid()) parentItem = m_rootItem;
else parentItem = static_cast<Item*>(parent.internalPointer());
return parentItem->children().length();
}
const QModelIndex DerivedModel::indexFromName(const QString& name){
//make a match based on the name
//and return 1st match
QModelIndex index = match(DerivedModel::index(0,0,QModelIndex()),
Qt::DisplayRole, name, 1,
Qt::MatchFlags(Qt::MatchExactly|Qt::MatchRecursive))
.value(0);
return index;
}
void DerivedModel::addItem(const QString& name, Item* parent){
//check parent
if(!parent) parent = m_rootItem;
//create the item
//will be deleted once parent is deleted
new Item(name, parent);
}
Item.h:
#ifndef ITEM_H
#define ITEM_H
#include <QString>
#include <QList>
#include <QDebug>
class Item {
public:
Item(const QString& name, Item* parent=nullptr) :
m_name(name), m_parent(parent){
//add as child to parent
if(parent) parent->addChild(this);
//set the flag to enable selection
m_flags = Qt::ItemIsSelectable;
qDebug() << "Created Item "+name;
};
~Item(){
//delete children
for (auto& child : m_children){
delete child;
}
};
//get the name
const QString& name() const {return m_name;}
//get the flags
const Qt::ItemFlags& flags() const {return m_flags;}
//gte the parent
Item* parent() const {return m_parent;}
//get the children
const QList<Item*>& children() {return m_children;}
//add a child
void addChild(Item* item) {m_children.append(item);}
private:
//name
QString m_name;
//flags
Qt::ItemFlags m_flags;
//parent
Item* m_parent;
//list og children
QList<Item*> m_children;
};
#endif
Scene.h:
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
//fwd dec
QT_FORWARD_DECLARE_CLASS(QItemSelection)
QT_FORWARD_DECLARE_CLASS(QGraphicsRectItem)
class Scene : public QGraphicsScene {
public:
Scene(QObject* parent);
virtual ~Scene(){}
public slots:
//pass the selection to the squares
void setSelection(const QItemSelection& selected, const QItemSelection& deselected);
};
#endif
Scene.cpp:
#include "Scene.h"
#include "DerivedModel.h"
#include "Item.h"
#include <QItemSelectionModel>
#include <QGraphicsRectItem>
#include <QRect>
#include <QDebug>
Scene::Scene(QObject* parent) : QGraphicsScene(parent)
{
//connect to the models selection change
connect(DerivedModel::instance().selectionModel(), &QItemSelectionModel::selectionChanged,
this, &Scene::setSelection);
}
void Scene::setSelection(const QItemSelection& selected, const QItemSelection& deselected){
Q_UNUSED(deselected);
//testing changes
int A = selected.size();
int B = selected.indexes().size();
QModelIndex index = selected.value(0).topLeft();
QString name = "";
if(index.isValid()) name = static_cast<Item*>(index.internalPointer())->name();
qDebug() << "Scene recieved item selection change";
qDebug() << "Number of selected QItemRanges from source = "+QString::number(A);
qDebug() << "Number of selected INDEXES from source = "+QString::number(B);
qDebug() << "Manually accessd 1st index in 1st range returns item named: "+name;
}
Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
//fwd dec
QT_FORWARD_DECLARE_CLASS(QPushButton)
QT_FORWARD_DECLARE_CLASS(QVBoxLayout)
QT_FORWARD_DECLARE_CLASS(QHBoxLayout)
QT_FORWARD_DECLARE_CLASS(QGraphicsView)
class DerivedModel;
class Scene;
class Widget : public QWidget{
public:
Widget(QWidget* parent=nullptr);
virtual ~Widget(){}
private slots:
//button toggle alot
void toggle(bool state);
private:
//layout
QVBoxLayout* m_mainVBLayout;
//horizontal layout for the buttons
QHBoxLayout* m_HBButtonsLayout;
//GraphicsView widget for the scene
QGraphicsView* m_graphicsView;
//the graphics scene recieving the change event where the problem is
Scene* m_scene;
//push buttons
QPushButton* m_button1;
QPushButton* m_button2;
//the DerivedModel
DerivedModel* m_model;
};
#endif
Widget.cpp:
#include "Widget.h"
#include "DerivedModel.h"
#include "Scene.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGraphicsView>
#include <QDebug>
#include <QItemSelection>
Widget::Widget(QWidget* parent) : QWidget(parent)
,m_mainVBLayout(nullptr)
,m_HBButtonsLayout(nullptr)
,m_graphicsView(nullptr)
,m_scene(nullptr)
,m_button1(nullptr)
,m_button2(nullptr)
,m_model(nullptr)
{
//init the DerivedModel
m_model = new DerivedModel(this);
//add two items to the model
m_model->addItem("A");
m_model->addItem("B");
//create the main layout
m_mainVBLayout = new QVBoxLayout(this);
//create the buttons layout
m_HBButtonsLayout = new QHBoxLayout;
//add it to the main layout
m_mainVBLayout->addLayout(m_HBButtonsLayout);
//create the buttons
m_button1 = new QPushButton("A", this);
m_button2 = new QPushButton("B", this);
//set them to be checkable
m_button1->setCheckable(true);
m_button2->setCheckable(true);
//connect their signals
connect(m_button1, &QPushButton::toggled, this, &Widget::toggle);
connect(m_button2, &QPushButton::toggled, this, &Widget::toggle);
//add them to the layout
m_HBButtonsLayout->addWidget(m_button1);
m_HBButtonsLayout->addWidget(m_button2);
//create the graphics view
m_graphicsView = new QGraphicsView(this);
//create the scene
m_scene = new Scene(this);
m_scene->setSceneRect(QRect(0,0,50,25));
//set its scene
m_graphicsView->setScene(m_scene);
//add the graphics view to the layout
m_mainVBLayout->addWidget(m_graphicsView);
}
void Widget::toggle(bool state){
//get the sender
QPushButton* button(nullptr);
if(sender()==m_button1) button = m_button1;
else button = m_button2;
//get the name of the item related to the button to change
QString name = button->text();
//get the index based on the name
//im using the instance of the DerivedModel because this is how I implement it in my project;
QModelIndex itemIndex = DerivedModel::instance().indexFromName(name);
//check if index is valid
if(!itemIndex.isValid()){
qDebug() << "Index for item "+name+" not valid!";
return;
}
else
qDebug() << "Found Item :)";
//create a QItemSelection as how it is in my project
QItemSelection selection;
//add the index to the selection
selection.select(itemIndex, itemIndex);
//check the state
if(state){
//add to the selection
DerivedModel::instance().selectionModel()->select(selection, QItemSelectionModel::Select);
}
else{
//remove from selection
DerivedModel::instance().selectionModel()->select(selection, QItemSelectionModel::Deselect);
}
}

Ok, so I found the culprit :)
In case anybody else has the same problem, my error was in the ::flags() function of my derived QAbstractItemModel class:
Inside the definition I didnt call the base class QAbstractItemModel::flags(index) function, once I called that instead of returning the flags myself all went well.
So I think that as long as your item has a Qt::flags flags() function that the model can call, you dont have to reimplement the QAbstractItemModel::flags() function.
It seems that the model is quering the flags through the QModelIndex::flags() function anyway.
Thanks you "Ezee" and "Kuba Ober" for willing to help.

My issue was that I was not calling the flags function of the inherited class.
def flags(self, index):
super_flags = super().flags(index)
flags = Qt.ItemIsEnabled
node = index.internalPointer()
if index.column() == 0:
flags |= Qt.ItemIsUserCheckable
if node.parent == self._rootNode:
flags |= Qt.ItemIsAutoTristate
return flags|super_flags

Related

QComboBox in QItemDelegate to show only the portion corresponding to other column

I have two MySQL tables with one-to-many relations.
Table si:
id integer primary key auto_increment,
...
cur_verify_date date,
...
Table verify:
...
si_id integer, -- id in 'si'
verify_date date,
...
So I need a combobox delegate for a table si in QTableView to choose items of verify_date only with si_id for corresponding id, different items in each row. However, the delegates can have, as I suppose, only identical values for each row. Is there a way to do it in the way I need?
Yes, you can do that with QItemDelegate, I would say that's your main solution when you want to show combobox in QTableView.
Check is signature of createEditor method from QAbstractItemDelegate:
https://doc.qt.io/qt-5/qabstractitemdelegate.html#createEditor
You can use QModelIndex parameter to define custom values for each row in your combobox.
While actual implementation will depend on your implementation of your model, you can check this simple example of that idea.
#include <QAbstractTableModel>
#include <QApplication>
#include <QTableView>
#include <QComboBox>
#include <QStyledItemDelegate>
class DummyModel : public QAbstractTableModel {
int rowCount(const QModelIndex& parent = QModelIndex()) const override
{
return 5;
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override
{
return 2;
}
Qt::ItemFlags flags(const QModelIndex& index) const override
{
return __super::flags(index) | Qt::ItemIsEditable;
}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (role == Qt::DisplayRole && index.column() == 0)
return index.row();
return {};
}
};
class ComboBoxItemDelegate : public QStyledItemDelegate {
public:
ComboBoxItemDelegate(QObject* parent = nullptr)
: QStyledItemDelegate(parent) {};
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override
{
QComboBox* cb = new QComboBox(parent);
//place to query database for actual values
const auto value = index.model()->index(index.row(), 0).data(Qt::DisplayRole).toString();
cb->addItem(value);
cb->addItem(value);
return cb;
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
DummyModel model;
QTableView table_view;
table_view.setModel(&model);
ComboBoxItemDelegate cb_delegate;
table_view.setItemDelegateForColumn(1, &cb_delegate);
table_view.show();
return app.exec();
}

QStyledItemDelegate: commit QComboBox value to model on click

I am setting a QStyledItemDelegate on my model for a particular field, and returning a QComboBox from QStyledItemDelegate::createEditor
QComboBox* createEditor(QWidget* parent)
{
QComboBox* cb = new QComboBox(parent);
cb->addItem("UNDEFINED");
cb->addItem("TEST");
cb->addItem("OSE");
cb->addItem("TSE");
return cb;
}
void setEditorData(QWidget* editor, const QModelIndex& index)
{
QComboBox* cb = qobject_cast<QComboBox*>(editor);
if (!cb)
throw std::logic_error("editor is not a combo box");
QString value = index.data(Qt::EditRole).toString();
int idx = cb->findText(value);
if (idx >= 0)
cb->setCurrentIndex(idx);
cb->showPopup();
}
This is working fine, and when I select the field in question I am shown a combo box.
When I select an option from the drop-down list, the combobox closes and the item is displayed with a drop-down icon next to it:
At this point I would like the QStyledItemDelegate::setModelData function to be called, so that selecting an item in the list commits the data to the model.
However, I am required to first press Enter to commit the data (whereby the drop-down icon disappears)
void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index)
{
QComboBox* cb = qobject_cast<QComboBox*>(editor);
if (!cb)
throw std::logic_error("editor is not a combo box");
model->setData(index, cb->currentText(), Qt::EditRole);
}
Question:
How can I configure my QComboBox to automatically commit the data when the user selects an item in the list and the combobox list closes, rather than requiring the additional press of Enter?
You have to issue the signal commitData and closeEditor when an item is selected as shown in the following example:
#include <QApplication>
#include <QStandardItemModel>
#include <QListView>
#include <QStyledItemDelegate>
#include <QComboBox>
class ComboBoxDelegate: public QStyledItemDelegate{
public:
using QStyledItemDelegate::QStyledItemDelegate;
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
Q_UNUSED(option)
Q_UNUSED(index)
QComboBox* editor = new QComboBox(parent);
connect(editor, QOverload<int>::of(&QComboBox::activated),
this, &ComboBoxDelegate::commitAndCloseEditor);
editor->addItems({"UNDEFINED", "TEST", "OSE", "TSE"});
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const{
QComboBox* cb = qobject_cast<QComboBox*>(editor);
if (!cb)
throw std::logic_error("editor is not a combo box");
QString value = index.data(Qt::EditRole).toString();
int idx = cb->findText(value);
if (idx >= 0)
cb->setCurrentIndex(idx);
cb->showPopup();
}
private:
void commitAndCloseEditor(){
QComboBox *editor = qobject_cast<QComboBox *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QListView view;
QStandardItemModel model;
for(int i=0; i<10; i++){
model.appendRow(new QStandardItem("UNDEFINED"));
}
view.setItemDelegate(new ComboBoxDelegate(&view));
view.setModel(&model);
view.show();
return a.exec();
}

How to make some column non-editable and some column editable in QTableView?

I have the model MyModel : public QSqlTableModel.
I want to forbid editing certain columns of the table. I did this using the method flags(), but faced with a new problem. I need to insert a row in the database, and when I cause methods insertRow () and setData (), the method setData () returns 0 for not editable columns. Therefore, I can not fill data to inserted row.
I want to forbid editing certain columns for view, but not for the model.
Some code:
Qt::ItemFlags ApplicantTableModel::flags(const QModelIndex &index) const
{
if(index.column() == 9 || index.column() == 10)
if(index.column() == 9 && index.data() == 0)
return Qt::ItemIsEnabled|Qt::ItemIsSelectable;
else
return Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsEditable;
else return Qt::ItemIsEnabled|Qt::ItemIsSelectable;
}
I fix it in next way. I created delegate.
QWidget *StatusDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.column() == 9){
QComboBox* editor = new QComboBox(parent);
editor->addItem(tr("Відраховано"));
editor->addItem(tr("Допущено"));
editor->addItem(tr("Бюджет"));
editor->addItem(tr("Контракт"));
editor->setAutoFillBackground(true);
return editor;
}
else return 0;
}
Given the information you left, I created an example widget, which shows that setData() even works on non editable indexes.
Model
class MyModel : public QStandardItemModel
{
public:
MyModel(QObject* parent = 0)
: QStandardItemModel(parent)
{}
Qt::ItemFlags flags(const QModelIndex &index) const {
if(index.column() < 5)
return Qt::ItemIsEnabled|Qt::ItemIsSelectable;
else
return Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsEditable;
}
};
Table Widget
// .h
class MyTableWidget : public QWidget
{
Q_OBJECT
public:
MyTableWidget(QWidget* parent = 0);
private slots:
void onEditTextChanged(QString const&);
private:
void initWidgets();
void initLayout();
QTableView* table_view_;
MyModel* table_model_;
QLineEdit* table_edit_;
};
// .cc
MyTableWidget::MyTableWidget(QWidget* parent)
: QWidget(parent)
, table_view_(0)
, table_model_(0)
, table_edit_(0)
{
initWidgets();
initLayout();
}
void MyTableWidget::onEditTextChanged(QString const& text)
{
foreach(QModelIndex index, table_view_->selectionModel()->selectedIndexes())
table_model_->setData(index, text);
}
void MyTableWidget::initWidgets()
{
table_view_ = new QTableView(this);
table_edit_ = new QLineEdit(this);
table_model_ = new MyModel;
table_model_->setColumnCount(10);
table_model_->setRowCount(10);
for(int c = 0; c < table_model_->columnCount(); ++c) {
for(int r = 0; r < table_model_->rowCount(); ++r) {
table_model_->setData(table_model_->index(r,c), QString("foo"));
}
}
table_view_->setModel(table_model_);
connect(table_edit_, SIGNAL(textChanged(QString const&)),
this, SLOT(onEditTextChanged(QString)));
}
void MyTableWidget::initLayout()
{
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(table_view_);
layout->addWidget(table_edit_);
setLayout(layout);
}
Leaving out the Qt::ItemIsEditable flag will only prevent editing by any caller that handles this flag. For instance, Qt delegates check flags() before they create the editor for modifying cell values. This prevents from ever calling setData(). If you call setData() yourself there should be no problem in editing the data.
I am assuming your error lies somewhere else. Did you overwrite setData() to handle flags()? Did you check if the ModelIndex you are handing in is correct?

How to build the Layout from the Properties frame in QtDesigner?

How can I build the Layout used by QtCreator in Tools->Options for my own application? It should look like this, but with another content:
How can I do this using C++/Qt using the QtDesigner integrated in QtCreator?
I just found the solution! I needed to use a QListView with a QStringListModel in it. To set the Item Size and Icons manually, I needed to subclass QStringListModel and QStyledItemDelegate:
// ItemDelegate to set item size manually
class MyItemDelegate : public QStyledItemDelegate
{
public:
virtual QSize sizeHint (const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize suggestion = QStyledItemDelegate::sizeHint(option, index);
return QSize(suggestion.width(), 30);
}
};
// StringListModel to allow setting images
class MyStringListModel : public QStringListModel
{
public:
virtual QVariant data (const QModelIndex &index, int role) const
{
if (role == Qt::DecorationRole)
{
QString value = stringList().at(index.row());
if (value == "new")
return add;
else
return db;
}
else
return QStringListModel::data(index, role);
}
private:
QIcon db = QIcon::fromTheme("server-database");
QIcon add = QIcon::fromTheme("list-add");
};
Then, I could update my QListView (that was created by Qt):
MyStringListModel * model = new MyStringListModel();
model->setStringList(QStringList() << "test" << "new");
ui->databases->setModel(model);
ui->databases->setItemDelegate(new MyItemDelegate());

Qt Using Custom QItemDelegate for QTableView

I followed the Spin Box Delegate tutorial, which Qt provides, to try to implement my own QItemDelegate. It would be used to specify a QComboBox to represent data in a QTableView cell but it is not working.
My biggest problem is that I don't know when my QItemDelegate is going to be utilized.
when itemModel->setData() is used or when itemModel->setItem(). I would suspect setItem() because I reimplemented a QItemDelegate (emphasis on the "Item") but the tutorial uses setData() and it works fine.
I know that if the specified QItemDelegate does not work it uses the default one but how do I now that the one I specified did not work?
when should I suspect for QTableView to use my delegate. I would like to specify which delegates to use for each cell. Is this possible or does the QTableView only use one delegate throughout?
How would I specify the items to populate the QComboBox once it gets displayed by the QTableView?
I implemented QItemDelegate here:
the part where I try to add the cell which is suppose to use the QComboBox is under the comment "Enabled" in mainwindow.cpp further down this post.
qcomboboxitemdelegate.h
#ifndef QCOMBOBOXITEMDELEGATE_H
#define QCOMBOBOXITEMDELEGATE_H
#include <QItemDelegate>
#include <QComboBox>
class QComboBoxItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit QComboBoxItemDelegate(QObject *parent = 0);
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index);
void setEditorData(QWidget *editor, const QModelIndex &index);
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index);
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index);
signals:
private:
};
#endif // QCOMBOBOXITEMDELEGATE_H
qcomboboxitemdelegate.cpp
#include "qcomboboxitemdelegate.h"
#include <QDebug>
QComboBoxItemDelegate::QComboBoxItemDelegate(QObject *parent)
: QItemDelegate(parent)
{
}
QWidget* QComboBoxItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) {
// create widget for use
QComboBox* comboBox = new QComboBox(parent);
return comboBox;
}
void QComboBoxItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) {
// update model widget
QString value = index.model()->data(index, Qt::EditRole).toString();
qDebug() << "Value:" << value;
QComboBox* comboBox = static_cast<QComboBox*>(editor);
comboBox->setCurrentIndex(comboBox->findText(value));
}
void QComboBoxItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) {
// store edited model data to model
QComboBox* comboBox = static_cast<QComboBox*>(editor);
QString value = comboBox->currentText();
model->setData(index, value, Qt::EditRole);
}
void QComboBoxItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) {
editor->setGeometry(option.rect);
}
mainwindow.cpp : this is where I initialize the QStandardItemModel
void MainWindow::init() {
itemModel = new QStandardItemModel(this);
}
void MainWindow::setupUi() {
this->setWindowTitle("QAlarmClock");
QStringList labelList;
labelList << "Alarm Name" << "Time" << "Enabled";
itemModel->setHorizontalHeaderLabels(labelList);
ui->tableView->setModel(itemModel);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableView->setItemDelegate(comboBoxItemDelegate);
}
void MainWindow::on_actionNew_triggered() {
alarmDialog = new AlarmDialog(this);
connect(alarmDialog, SIGNAL(on_close()), this, SLOT(on_alarmDialog_close()));
alarmDialog->exec();
}
mainwindow.cpp : this is where I update QStandardItemModel
void MainWindow::on_alarmDialog_close() {
QString alarmName = alarmDialog->getAlarmName();
QDateTime alarmDateTime = alarmDialog->getDateTime();
itemModel->insertRow(itemModel->rowCount());
int rowCount = itemModel->rowCount();
// Alarm Name
QStandardItem* alarmItem = new QStandardItem(QIcon("res/alarmclock.ico"), alarmName);
itemModel->setItem(rowCount - 1 , 0, alarmItem);
// Date Time
QStandardItem* dateTimeItem = new QStandardItem();
dateTimeItem->setText(alarmDateTime.toString());
dateTimeItem->setEditable(false);
itemModel->setItem(rowCount - 1, 1, dateTimeItem);
// Enabled
QStandardItem* enabledItem = new QStandardItem();
QList<QStandardItem*> optionList;
optionList << new QStandardItem("Enabled") << new QStandardItem("Disabled");
enabledItem->appendRows(optionList);
itemModel->setItem(rowCount - 1, 2, enabledItem);
}
Edit 1
qcomboboxdelegate.cpp
QWidget* QComboBoxItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) {
// create widget for use
qDebug() << "Column: " << index.column();
if (index.column() == 2) {
QComboBox* comboBox = new QComboBox(parent);
QStringList values;
values << "Enabled" << "Disabled";
comboBox->addItems(values);
return comboBox;
} else {
return QItemDelegate::createEditor(parent, option, index);
}
}
mainwindow.cpp
void MainWindow::on_alarmDialog_close() {
QList<QStandardItem*> row;
QString alarmName = alarmDialog->getAlarmName();
QDateTime alarmDateTime = alarmDialog->getDateTime();
QString status = "Enabled";
// Alarm Name
QStandardItem* alarmItem = new QStandardItem(QIcon("res/alarmclock.ico"), alarmName);
row << alarmItem;
// Date Time
QStandardItem* dateTimeItem = new QStandardItem();
dateTimeItem->setText(alarmDateTime.toString());
dateTimeItem->setEditable(false);
row << dateTimeItem;
// Enabled
QStandardItem* statusItem = new QStandardItem(status);
row << statusItem;
itemModel->appendRow(row);
}
First, you should have a description of your model columns:
enum Columns
{
COL_NAME,
COL_TIME,
COL_STATUS
}
Your delegate should only work for the last column.
Here is an example of how you can populate your model:
for (int i = 0; i < 5; ++i)
{
QStandardItem *itemName = new QStandardItem(QString("name %1").arg(i));
QStandardItem *itemTime = new QStandardItem(QString("time %1").arg(i));
QString status;
if (i % 2 == 0)
{
status = "Enabled";
}
else
{
status = "Disabled";
}
QStandardItem *itemStatus = new QStandardItem(status);
QList<QStandardItem*> row;
row << itemName << itemTime << itemStatus;
model->appendRow(row);
}
As I said, your delegate should only work for the last column. So all methods you have reimplemented should have a column check like this:
QWidget* QComboBoxItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index)
{
if (index.column() == COL_STATUS)
{
QStringList values;
values << "Enabled" << "Disabled";
QComboBox* comboBox = new QComboBox(parent);
comboBox->addItems(values);
return comboBox;
}
else
{
return QItemDelegate::createEditor(parent, option, index);
}
}
You should add this check to the other methods: if the current column is not the status column, the base class (QItemDelegate) implementation should be used.
Then you set your delegate to your view:
ui->tableView->setItemDelegate(new ComboBoxDelegate);
If you do everything right, a combo Box will appear in the last column if you try to edit its values.
Even more simply; I found QTableView::setItemDelegateForColumn() to work admirably for a column. For example, in your MainWindow, you could make a member:
QComboBoxItemDelegate dgtComboDelegate;
Then, in your ctor, or init(), you could have
ui->tableView->setItemDelegateForColumn(2, dgtComboDelegate);
If you wanted that to happen for a single cell, that's when you need to test on the index.column() and index.row().
You know, you don't have to create a QTableView to do this either. E.g., see the ?:
Qt - Centering a checkbox in a QTable
The OP doesn't give the declaration for a table widget or view; but it does have the QTableView tag. It should work equally well for either.
In the former case, you can do ui->tableWidget->setItemDelegateForColumn(2, dgtComboDelegate); and never have to make your own model. Just use setData() on the items you create (or even later, for that matter,) to initialize their values.
So I figured out that I did not override the correct function prototypes..! I forgot that they
had const in the prototype meaning that I was not overriding any functions so it was using the default ones. Here are the correct virtual functions that have to be re-implemented: http://qt-project.org/doc/qt-5.0/qtwidgets/qitemdelegate.html