Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QTableView & CheckBox delegate alignmnent
QtWS25 Last Chance

QTableView & CheckBox delegate alignmnent

Scheduled Pinned Locked Moved General and Desktop
43 Posts 4 Posters 37.0k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    hsfougaris
    wrote on last edited by
    #1

    I have a QSqlTableModel that I am trying to use with a QTableView.
    As I have some columns that contain 1/0 which means true/false in my case, I need to display check boxes instead of the numbers.

    I created a delegate, but I'm having an alignment problem: when it is displayed it is centered as intended, but when editing it is displayed to the left (with another checkbox visible in the center).

    Here is my code:
    @
    BooleanItemDelegate::BooleanItemDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
    {
    }

    QWidget *BooleanItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    if (index.isValid()) {
    QCheckBox *cb =new QCheckBox(parent);
    return cb;
    } else {
    return QStyledItemDelegate::createEditor(parent, option, index);
    }
    }

    void BooleanItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
    if(index.isValid())
    {
    int value = index.model()->data(index, Qt::DisplayRole).toInt();
    QCheckBox checkBox = static_cast<QCheckBox>(editor);
    if(value == 1) {
    checkBox->setCheckState(Qt::Checked);
    } else {
    checkBox->setCheckState(Qt::Unchecked);
    }
    }
    else
    {
    QStyledItemDelegate::setEditorData(editor, index);
    }

    }

    void BooleanItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
    if(index.isValid())
    {
    QCheckBox checkBox = static_cast<QCheckBox>(editor);
    int value;
    if(checkBox->checkState() == Qt::Checked)
    value = 1;
    else
    value = 0;

        model->setData(index, value);
    }
    else
    {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
    

    }

    QRect BooleanItemDelegate::CheckBoxRect(const QStyleOptionViewItem &view_item_style_options) {
    QStyleOptionButton check_box_style_option;
    QRect check_box_rect = QApplication::style()->subElementRect( QStyle::SE_CheckBoxIndicator, &check_box_style_option);
    QPoint check_box_point(view_item_style_options.rect.x() + view_item_style_options.rect.width() / 2 - check_box_rect.width() / 2,
    view_item_style_options.rect.y() + view_item_style_options.rect.height() / 2 -
    check_box_rect.height() / 2);
    return QRect(check_box_point, check_box_rect.size());
    }

    void BooleanItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {

     int value = index.model()->data(index, Qt::DisplayRole).toInt();
    
     QStyleOptionButton check_box_style_option;
     check_box_style_option.state |= QStyle::State_Enabled;
     if (value == 1) {
         check_box_style_option.state |= QStyle::State_On;
     } else {
         check_box_style_option.state |= QStyle::State_Off;
     }
     check_box_style_option.rect = BooleanItemDelegate::CheckBoxRect(option);
    
     QApplication::style()->drawControl(QStyle::CE_CheckBox, &check_box_style_option, painter);
    

    }
    @

    Can somone please tell me what I am doing wrong?

    Thanks,
    Harry

    If you can't say what you mean, you'll never be able to mean what you say.

    1 Reply Last reply
    0
    • G Offline
      G Offline
      giesbert
      wrote on last edited by
      #2

      perhaps you should not use the checkbox itself, try to make the cell itself checkable.
      As you want to use a QSqlTableModel, you could use a custom proxy model, derived from QSortFilterProxyModel and add the flag there. then editing is not done via a real combo box :-)

      Nokia Certified Qt Specialist.
      Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

      1 Reply Last reply
      0
      • A Offline
        A Offline
        andre
        wrote on last edited by
        #3

        Indeed. A proxy model is the way to go here. You only need to reimplement the data(), setData() and the flags() methods to make the column user checkable with a checkbox. That is much simpler than using a custom delegate.

        1 Reply Last reply
        0
        • G Offline
          G Offline
          giesbert
          wrote on last edited by
          #4

          If the check sign should be centered, the delegate is in fact needed...
          Otherwise it's in the front of the cell

          Nokia Certified Qt Specialist.
          Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

          1 Reply Last reply
          0
          • H Offline
            H Offline
            hsfougaris
            wrote on last edited by
            #5

            But that would mean I'd need a custom proxy model for every table I use, doesn't it?
            I've been trying to avoid that.

            If I had to do that, would it make more sense QSqlTableModel for every table?
            What would be the benefits in each case?

            If you can't say what you mean, you'll never be able to mean what you say.

            1 Reply Last reply
            0
            • A Offline
              A Offline
              andre
              wrote on last edited by
              #6

              No, you can make a generic proxy model that can make any column checkable, and simply reuse that.

              1 Reply Last reply
              0
              • H Offline
                H Offline
                hsfougaris
                wrote on last edited by
                #7

                Do you have a link of an example handy? I would think I'd have to tweak ony the flags() functions....
                Thanks, Harry

                If you can't say what you mean, you'll never be able to mean what you say.

                1 Reply Last reply
                0
                • G Offline
                  G Offline
                  giesbert
                  wrote on last edited by
                  #8

                  If you only tweak flags, you will never show a checked state.

                  That's why you have to also implement data and setData.

                  Nokia Certified Qt Specialist.
                  Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                  1 Reply Last reply
                  0
                  • H Offline
                    H Offline
                    hsfougaris
                    wrote on last edited by
                    #9

                    Ok I found something that seems to work.
                    (based on this http://www.qtcentre.org/archive/index.php/t-18675.html)

                    I'm putting the code here, in case it helps someone else:

                    The basic idea is that there is something like a QList that holds the indexes of the columns that you want to have checkboxes (I'm already thinking of adding another QList for readonly columns).
                    Actual usage would be
                    @
                    CheckableSortFilterProxyModel *cfpm = new CheckableSortFilterProxyModel(this);
                    QList<int> boolCols;
                    boolCols.append( usrModel->fieldIndex("isActive") );
                    boolCols.append( usrModel->fieldIndex("isOk") );
                    cfpm->setParameters(boolCols);
                    cfpm->setSourceModel( mySqlTableModel );
                    myTableView->setModel(cfpm);
                    @

                    Here is the code:

                    checkablesortfilterproxymodel.h:
                    @
                    #ifndef CHECKABLESORTFILTERPROXYMODEL_H
                    #define CHECKABLESORTFILTERPROXYMODEL_H

                    #include <QSortFilterProxyModel>

                    class CheckableSortFilterProxyModel : public QSortFilterProxyModel
                    {
                    Q_OBJECT
                    public:
                    explicit CheckableSortFilterProxyModel(QObject *parent = 0);

                    void setParameters(QList<int> boolCols);
                    

                    protected:
                    QVariant data(const QModelIndex &index, int role) const;
                    bool setData(const QModelIndex &index, const QVariant &value, int role);
                    Qt::ItemFlags flags ( const QModelIndex & index ) const;

                    signals:

                    public slots:

                    private:
                    QList<int> booleanSet;

                    };

                    #endif // CHECKABLESORTFILTERPROXYMODEL_H
                    @

                    checkablesortfilterproxymodel.cpp:
                    @
                    #include "checkablesortfilterproxymodel.h"

                    CheckableSortFilterProxyModel::CheckableSortFilterProxyModel(QObject *parent) :
                    QSortFilterProxyModel(parent)
                    {
                    }

                    void CheckableSortFilterProxyModel::setParameters(QList<int> boolCols) {
                    booleanSet.clear();
                    if (!boolCols.isEmpty()) {
                    foreach(int column , boolCols)
                    {
                    booleanSet.append(column);
                    }
                    }
                    }

                    QVariant CheckableSortFilterProxyModel::data(const QModelIndex &index, int role) const {
                    if(!index.isValid())
                    return QVariant();

                    if(booleanSet.contains(index.column()) && (role == Qt::CheckStateRole || role == Qt::DisplayRole)) {
                        if (role == Qt::CheckStateRole)
                            return index.data(Qt::EditRole).toBool() ? QVariant(Qt::Checked) : QVariant(Qt::Unchecked);
                        else if (role == Qt::DisplayRole)
                            return QVariant();
                    }
                    else
                        return QSortFilterProxyModel::data(index,role);
                    

                    }

                    bool CheckableSortFilterProxyModel::setData(const QModelIndex &index, const QVariant &value, int role) {
                    if(!index.isValid())
                    return false;

                    if(booleanSet.contains(index.column()) && role==Qt::CheckStateRole)
                    {
                        QVariant data = (value.toInt()==Qt::Checked) ? QVariant(1) : QVariant (0);
                        return QSortFilterProxyModel::setData(index, data, Qt::EditRole);
                    }
                    else
                        return QSortFilterProxyModel::setData(index,value,role);
                    

                    }

                    Qt::ItemFlags CheckableSortFilterProxyModel::flags ( const QModelIndex & index ) const {
                    if(!index.isValid())
                    return Qt::ItemIsEnabled;

                    if(booleanSet.contains(index.column()))
                        return Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsEnabled;
                    else
                        return QSortFilterProxyModel::flags(index);
                    

                    }
                    @

                    If you can't say what you mean, you'll never be able to mean what you say.

                    1 Reply Last reply
                    0
                    • H Offline
                      H Offline
                      hsfougaris
                      wrote on last edited by
                      #10

                      I can easily (I think) make a column readonly with the same logic.

                      If I wanted to have password fields (in the sense where the actual data is not displayed), would I need to use a delegate, or can it somehow be done with the proxy model?

                      If you can't say what you mean, you'll never be able to mean what you say.

                      1 Reply Last reply
                      0
                      • G Offline
                        G Offline
                        giesbert
                        wrote on last edited by
                        #11

                        The pure display can be done in the same way, just return some stars and not the text.
                        But to enable password like editing, you need a delegate.

                        Nokia Certified Qt Specialist.
                        Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                        1 Reply Last reply
                        0
                        • H Offline
                          H Offline
                          hsfougaris
                          wrote on last edited by
                          #12

                          Readonly works fine.
                          If I add another list (eg. readonlySet)

                          in the flags function, all I need to add is
                          @
                          else if (readonlySet.contains(index.column()))
                          return Qt::ItemIsSelectable;
                          @

                          For the password thing, all I've been able to do is return '***' when the columns is in the passwordSet list. When the user clicks on it, the actual text is shown.

                          If you can't say what you mean, you'll never be able to mean what you say.

                          1 Reply Last reply
                          0
                          • H Offline
                            H Offline
                            hsfougaris
                            wrote on last edited by
                            #13

                            One thing still not working is that the checkboxes are not aligned in the center.
                            How should I handle that?

                            If you can't say what you mean, you'll never be able to mean what you say.

                            1 Reply Last reply
                            0
                            • H Offline
                              H Offline
                              hsfougaris
                              wrote on last edited by
                              #14

                              Another issue:
                              it doesn't work with a QSqlRelationalTableModel (I've been using a QSqlTableModel).

                              The lookup value is displayed correctly, but it is an editable text box, instead of a combo box.
                              I am using
                              @
                              myTableVw->setItemDelegate(new QSqlRelationalDelegate(myTableVw));
                              @
                              Any ideas?

                              If you can't say what you mean, you'll never be able to mean what you say.

                              1 Reply Last reply
                              0
                              • G Offline
                                G Offline
                                giesbert
                                wrote on last edited by
                                #15

                                For moving the check box to the center, a custom delegate is needed.
                                Also for editing the Password stuff with a password edit.

                                by the way, you should make a code sniuppet of this and add it to the wiki :-)

                                Nokia Certified Qt Specialist.
                                Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                                1 Reply Last reply
                                0
                                • H Offline
                                  H Offline
                                  hsfougaris
                                  wrote on last edited by
                                  #16

                                  I guess the checkbox can stay to the left if it will save me a delegate :)
                                  The issue with the SqlRelationalTableModel however is much more serious, and a deal breaker if it can't be resolved.

                                  If you can't say what you mean, you'll never be able to mean what you say.

                                  1 Reply Last reply
                                  0
                                  • H Offline
                                    H Offline
                                    hsfougaris
                                    wrote on last edited by
                                    #17

                                    I can't resist the urge to complain:
                                    It looks like another issue that will never be resolved (like other questions I've asked here and in the mailing list)...
                                    I mean are my questions that stupid? Most things desktop related and especially SQL stuff, seem to be so underdeveloped, you'd think it was developed by a different company.
                                    I've learnt to live with that, but the fact that noone from the Nokia developers (that read these message) bothers to acknowledge, concern or help with desktop issues, is very frustrating.

                                    I see pointless, endless discussions about the best way to draw a pixel, or the ill-fated mobile stuff, which would be all good, if such major gaps didn't exist.

                                    Look at this simple class I've almost done here: why doesn't it exist as part of Qt? There are hundreds (if not thousands) of messages/questions of people asking how to do checkboxes in a tableView.
                                    Each implements it differently, depending on Google's mood on the day they search for info.

                                    If you can't say what you mean, you'll never be able to mean what you say.

                                    1 Reply Last reply
                                    0
                                    • G Offline
                                      G Offline
                                      giesbert
                                      wrote on last edited by
                                      #18

                                      Hey hsfougaris,

                                      a checkable cell is described in the docs with the Qt::ItemIsUserCheckable flag. This is also described in the docs and perhaps in the examples. What else should they do? They have a standard way.

                                      And as a side note: this is a community forum, not a nokia developers forum. If spome of the Trolls hang around here, it's in their free time.

                                      Nokia Certified Qt Specialist.
                                      Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                                      1 Reply Last reply
                                      0
                                      • H Offline
                                        H Offline
                                        hsfougaris
                                        wrote on last edited by
                                        #19

                                        Well, how can you easily use it when using any QSql** models (which is a very common case one would think)? You have to subclass every time...

                                        I also know this is a community forum, that people like you devote a lot of resources to, and manage to help many people.
                                        What annoys me is they seem to respond to many questions about almost everything, except desktop and database related stuff.

                                        thanks,
                                        harry

                                        If you can't say what you mean, you'll never be able to mean what you say.

                                        1 Reply Last reply
                                        0
                                        • H Offline
                                          H Offline
                                          hsfougaris
                                          wrote on last edited by
                                          #20

                                          Back to the main issue, I found this post http://lists.qt.nokia.com/pipermail/qt-interest/2009-January/001833.html which is pretty much about the same thing.

                                          It seems to be a bug in QSqlRelationalDelegate , and a workaround for the createEditor is discussed.
                                          But I can't seem to find the code.
                                          In src\sql\models\qsqlrelationaldelegate.cpp there is only the following
                                          @
                                          /*!
                                          \fn QWidget *QSqlRelationalDelegate::createEditor(QWidget *parent,
                                          const QStyleOptionViewItem &option,
                                          const QModelIndex &index) const
                                          \reimp
                                          */
                                          @
                                          Does anyone know where the actual implementation is?

                                          If you can't say what you mean, you'll never be able to mean what you say.

                                          1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved