Pergunta

I create a QTableview with a QStandardItemModel, after editing the QStandardItem the type changed from unsigned int to int. This behavior just happen to unsigned int and just while the user is editing it, other datatypes stay.

window.cpp

#include "window.h"
#include "ui_window.h"
#include <QTableView>
#include <QStandardItem>
#include <QDebug>

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

    QTableView *tblview = new QTableView(this);
    model = new QStandardItemModel(0,0);

    tblview->setModel(model);

    QStandardItem *data=new QStandardItem;
    data->setEditable(true);
    data->setData(QVariant((uint)1), Qt::DisplayRole);
    model->setItem(0, 0, data);
    tblview->show();

    QModelIndex index = model->index( 0, 0, QModelIndex() );

    tblview->setGeometry(0,0,200,200);

    //result QVariant(uint, 1)
    qDebug() << model->data(index);



    connect(model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(dataChanged(QStandardItem*)));
}

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

void Window::dataChanged(QStandardItem* stditem)
{
    //result
    //QVariant(int, 3)
    //expected result 
    //QVariant(uint, 3)
    qDebug() << model->data(stditem->index());

}

window.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QMainWindow>
#include <QStandardItem>

namespace Ui {
    class Window;
}

class Window : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::Window *ui;
    QStandardItemModel* model;

private slots:
    void dataChanged(QStandardItem*);
};

#endif // WINDOW_H
Foi útil?

Solução

The second qDebug() does not print nothing because you do not define the role. This will work:

qDebug() << stditem->data(Qt::DisplayRole);

Now concerning the conversion from an uint QVariant to an int after the edit. This is natural and can be explained as follows:

First you have a QVariant that is uint

QVariant v = QVariant((uint) 5)); // It is uint now... 

After the edit, the model changes its value with the int value that is entered

v = QVariant(10); // Now v is not uint anymore but int

In order to avoid it you should subclass the QStandardItemModel, and reimplement the setData function. There you should explicitly cast the new value to uint.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top