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. How to set alignment of QTableWidget columns
Forum Updated to NodeBB v4.3 + New Features

How to set alignment of QTableWidget columns

Scheduled Pinned Locked Moved Unsolved General and Desktop
14 Posts 3 Posters 26.4k 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.
  • VRoninV Offline
    VRoninV Offline
    VRonin
    wrote on last edited by
    #3

    I'll add 2 more:

    • tableWidget->model()->setData(tableWidget->model()->index(row,column),Qt::AlignCenter,Qt::TextAlignmentRole);
    • tableWidgetItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);

    "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
    ~Napoleon Bonaparte

    On a crusade to banish setIndexWidget() from the holy land of Qt

    JonBJ 1 Reply Last reply
    2
    • JonBJ JonB

      @sonichy
      https://stackoverflow.com/questions/15827886/set-default-alignment-for-cells-in-qtablewidget/15828907#15828907, http://www.codeprogress.com/cpp/libraries/qt/QTableWidgetSetCellAlignment.php, etc.

      sonichyS Offline
      sonichyS Offline
      sonichy
      wrote on last edited by
      #4

      @JonB
      Text can set when fill cell:

      QTableWidgetItem *TWI = new QTableWidgetItem(QString("%1:%2").arg(ds/60,2,10,QLatin1Char(' ')).arg(ds%60,2,10,QLatin1Char('0')));
      TWI->setTextAlignment(Qt::AlignRight|Qt::AlignVCenter);
      tableWidget_songlist->setItem(i,3,TWI);
      

      But how to set alignment of QWidget in cell ?

      https://github.com/sonichy

      1 Reply Last reply
      0
      • VRoninV VRonin

        I'll add 2 more:

        • tableWidget->model()->setData(tableWidget->model()->index(row,column),Qt::AlignCenter,Qt::TextAlignmentRole);
        • tableWidgetItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
        JonBJ Offline
        JonBJ Offline
        JonB
        wrote on last edited by JonB
        #5

        @VRonin
        The one I really like is given in https://stackoverflow.com/a/4959104/489865. That does it by column instead of by cell. However, comments there state (so I did not reference it):

        return QAbstractTableModel::data(index,role) is not possible I think.
        This answer was given in a simpler time, when grass was greener and sky was clearer. Please feel free to edit this answer

        Could you give us the corrected code for this in Qt now, kindly?

        VRoninV 1 Reply Last reply
        0
        • JonBJ JonB

          @VRonin
          The one I really like is given in https://stackoverflow.com/a/4959104/489865. That does it by column instead of by cell. However, comments there state (so I did not reference it):

          return QAbstractTableModel::data(index,role) is not possible I think.
          This answer was given in a simpler time, when grass was greener and sky was clearer. Please feel free to edit this answer

          Could you give us the corrected code for this in Qt now, kindly?

          VRoninV Offline
          VRoninV Offline
          VRonin
          wrote on last edited by
          #6

          @JonB said in How to set alignment of QTableWidget columns:

          Could you give us the corrected code for this in Qt now, kindly?

          My answer is still valid. that SO answer suggests subclassing the delegate and reimplement data, that's not what I'm doing

          But how to set alignment of QWidget in cell ?

          How are you setting this QWidget and why are you using a QWidget at all to simply display an image?!

          "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
          ~Napoleon Bonaparte

          On a crusade to banish setIndexWidget() from the holy land of Qt

          JonBJ 1 Reply Last reply
          0
          • VRoninV VRonin

            @JonB said in How to set alignment of QTableWidget columns:

            Could you give us the corrected code for this in Qt now, kindly?

            My answer is still valid. that SO answer suggests subclassing the delegate and reimplement data, that's not what I'm doing

            But how to set alignment of QWidget in cell ?

            How are you setting this QWidget and why are you using a QWidget at all to simply display an image?!

            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by
            #7

            @VRonin said in How to set alignment of QTableWidget columns:

            @JonB said in How to set alignment of QTableWidget columns:

            Could you give us the corrected code for this in Qt now, kindly?

            My answer is still valid. that SO answer suggests subclassing the delegate and reimplement data, that's not what I'm doing

            Sorry, yes, I know your answer is valid. My question to you (as an expert!) is: I much prefer setting something on the column once over setting on each item. So how would you rewrite the way he does it such that it is legal again in Qt5?

            VRoninV 1 Reply Last reply
            0
            • JonBJ JonB

              @VRonin said in How to set alignment of QTableWidget columns:

              @JonB said in How to set alignment of QTableWidget columns:

              Could you give us the corrected code for this in Qt now, kindly?

              My answer is still valid. that SO answer suggests subclassing the delegate and reimplement data, that's not what I'm doing

              Sorry, yes, I know your answer is valid. My question to you (as an expert!) is: I much prefer setting something on the column once over setting on each item. So how would you rewrite the way he does it such that it is legal again in Qt5?

              VRoninV Offline
              VRoninV Offline
              VRonin
              wrote on last edited by VRonin
              #8

              @JonB said in How to set alignment of QTableWidget columns:

              So how would you rewrite the way he does it such that it is legal again in Qt5?

              I'd subclass the delegate and reimplement paint changing 1 line

              class AlignDelegate : public QStyledItemDelegate{
              Q_OBJECT
              Q_DISABLE_COPY(AlignDelegate)
              public:
              explicit AlignDelegate(Qobject* parent = Q_NULLPTR) : QStyledItemDelegate(parent), m_alignment(Qt::AlignLeft){}
              void paint(QPainter *painter,const QStyleOptionViewItem &option, const QModelIndex &index) const
              {
                  Q_ASSERT(index.isValid());
                  QStyleOptionViewItem opt = option;
                  initStyleOption(&opt, index);
              opt.displayAlignment = m_alignment; // only line changed from default
                  const QWidget *widget = option.widget;
                  QStyle *style = widget ? widget->style() : QApplication::style();
                  style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
              }
              Qt::Alignment alignment() const {return m_alignment;}
              void setAlignment(Qt::Alignment align) {m_alignment=align;}
              private:
              Qt::Alignment m_alignment;
              };
              

              "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
              ~Napoleon Bonaparte

              On a crusade to banish setIndexWidget() from the holy land of Qt

              JonBJ 1 Reply Last reply
              1
              • VRoninV VRonin

                @JonB said in How to set alignment of QTableWidget columns:

                So how would you rewrite the way he does it such that it is legal again in Qt5?

                I'd subclass the delegate and reimplement paint changing 1 line

                class AlignDelegate : public QStyledItemDelegate{
                Q_OBJECT
                Q_DISABLE_COPY(AlignDelegate)
                public:
                explicit AlignDelegate(Qobject* parent = Q_NULLPTR) : QStyledItemDelegate(parent), m_alignment(Qt::AlignLeft){}
                void paint(QPainter *painter,const QStyleOptionViewItem &option, const QModelIndex &index) const
                {
                    Q_ASSERT(index.isValid());
                    QStyleOptionViewItem opt = option;
                    initStyleOption(&opt, index);
                opt.displayAlignment = m_alignment; // only line changed from default
                    const QWidget *widget = option.widget;
                    QStyle *style = widget ? widget->style() : QApplication::style();
                    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
                }
                Qt::Alignment alignment() const {return m_alignment;}
                void setAlignment(Qt::Alignment align) {m_alignment=align;}
                private:
                Qt::Alignment m_alignment;
                };
                
                JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by JonB
                #9

                @VRonin
                Oh my word! OK, fair enough, far too much for me to want to do in Python! I liked the guy's "one-liner" to set column alignment.... It was just the replacement for line:

                return QAbstractTableModel::data(index, role);
                

                (which a comment says "no longer works", and possibly to do with a QVariant) that I was looking for.

                VRoninV 1 Reply Last reply
                0
                • JonBJ JonB

                  @VRonin
                  Oh my word! OK, fair enough, far too much for me to want to do in Python! I liked the guy's "one-liner" to set column alignment.... It was just the replacement for line:

                  return QAbstractTableModel::data(index, role);
                  

                  (which a comment says "no longer works", and possibly to do with a QVariant) that I was looking for.

                  VRoninV Offline
                  VRoninV Offline
                  VRonin
                  wrote on last edited by VRonin
                  #10

                  @JonB Let's try this one if it's easier:

                  class AlignProxy : public QIdentityProxyModel{
                  Q_OBJECT
                  Q_DISABLE_COPY(AlignProxy)
                  public:
                  explicit AlignProxy(QObject* parent = Q_NULLPTR)  : QIdentityProxyModel(parent) , m_alignment(Qt::AlignLeft), m_alignColumn(0){}
                  Qt::Alignment alignment() const {return m_alignment;}
                  void setAlignment(Qt::Alignment align) {
                  if(align==m_alignment) return;
                  m_alignment=align;
                  alignmentChanged(m_alignment);
                  if(sourceModel())
                  dataChanged(index(0,m_alignColumn),index(rowCount(),m_alignColumn));
                  }
                  Q_SIGNAL void alignmentChanged(Qt::Alignment align);
                  Q_SIGNAL void alignedColumnChanged(int col);
                  int alignedColumn() const {return m_alignColumn;}
                  void setAlignedColumn(int col){
                  if(col==m_alignColumn) return;
                  const int oldCol=m_alignColumn;
                  m_alignColumn=col;
                  alignedColumnChanged(m_alignColumn);
                  if(sourceModel()){
                  dataChanged(index(0,m_alignColumn),index(rowCount(),m_alignColumn));
                  dataChanged(index(0,oldCol),index(rowCount(),oldCol));
                  }
                  }
                  QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE{
                  if(sourceModel() && role==Qt::TextAlignmentRole && index.column() == m_alignColumn) return m_alignment;
                  return QIdentityProxyModel::data(index,role);
                  }
                  private:
                  int m_alignColumn;
                  Qt::Alignment m_alignment;
                  };
                  

                  "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                  ~Napoleon Bonaparte

                  On a crusade to banish setIndexWidget() from the holy land of Qt

                  JonBJ 1 Reply Last reply
                  1
                  • VRoninV VRonin

                    @JonB Let's try this one if it's easier:

                    class AlignProxy : public QIdentityProxyModel{
                    Q_OBJECT
                    Q_DISABLE_COPY(AlignProxy)
                    public:
                    explicit AlignProxy(QObject* parent = Q_NULLPTR)  : QIdentityProxyModel(parent) , m_alignment(Qt::AlignLeft), m_alignColumn(0){}
                    Qt::Alignment alignment() const {return m_alignment;}
                    void setAlignment(Qt::Alignment align) {
                    if(align==m_alignment) return;
                    m_alignment=align;
                    alignmentChanged(m_alignment);
                    if(sourceModel())
                    dataChanged(index(0,m_alignColumn),index(rowCount(),m_alignColumn));
                    }
                    Q_SIGNAL void alignmentChanged(Qt::Alignment align);
                    Q_SIGNAL void alignedColumnChanged(int col);
                    int alignedColumn() const {return m_alignColumn;}
                    void setAlignedColumn(int col){
                    if(col==m_alignColumn) return;
                    const int oldCol=m_alignColumn;
                    m_alignColumn=col;
                    alignedColumnChanged(m_alignColumn);
                    if(sourceModel()){
                    dataChanged(index(0,m_alignColumn),index(rowCount(),m_alignColumn));
                    dataChanged(index(0,oldCol),index(rowCount(),oldCol));
                    }
                    }
                    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE{
                    if(sourceModel() && role==Qt::TextAlignmentRole && index.column() == m_alignColumn) return m_alignment;
                    return QIdentityProxyModel::data(index,role);
                    }
                    private:
                    int m_alignColumn;
                    Qt::Alignment m_alignment;
                    };
                    
                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by
                    #11

                    @VRonin
                    Thank you so much for your efforts to convince me, but nope! Unless it's a one-line rewrite of return QAbstractTableModel::data(index, role); such that it works in Qt5 ('coz from the comment that no longer works compared to "old" Qt), I'll stick to setting each QTableWidgetItem individually :)

                    VRoninV 1 Reply Last reply
                    0
                    • JonBJ JonB

                      @VRonin
                      Thank you so much for your efforts to convince me, but nope! Unless it's a one-line rewrite of return QAbstractTableModel::data(index, role); such that it works in Qt5 ('coz from the comment that no longer works compared to "old" Qt), I'll stick to setting each QTableWidgetItem individually :)

                      VRoninV Offline
                      VRoninV Offline
                      VRonin
                      wrote on last edited by VRonin
                      #12

                      @JonB The change is really just two lines:

                      QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE{
                      if(sourceModel() && role==Qt::TextAlignmentRole && index.column() == m_alignColumn) return m_alignment;
                      return QIdentityProxyModel::data(index,role);
                      }
                      

                      the rest is there to make it pretty and work dinamically

                      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                      ~Napoleon Bonaparte

                      On a crusade to banish setIndexWidget() from the holy land of Qt

                      JonBJ 1 Reply Last reply
                      2
                      • VRoninV VRonin

                        @JonB The change is really just two lines:

                        QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE{
                        if(sourceModel() && role==Qt::TextAlignmentRole && index.column() == m_alignColumn) return m_alignment;
                        return QIdentityProxyModel::data(index,role);
                        }
                        

                        the rest is there to make it pretty and work dinamically

                        JonBJ Offline
                        JonBJ Offline
                        JonB
                        wrote on last edited by JonB
                        #13

                        @VRonin
                        Ah ha! That's more like it, to my taste!

                        To be clear (excuse my ignorance, I'm a Qt learner! the docs page does not show how the QIdentityProxy is originally created), do you have to originally set up the QTableWidgets model to be a QIdentityProxyModel-wrapper around the originally-desired model? Like:

                        model = ...;
                        identityModel = QIdentityProxyModel();
                        identityModel->setSourceModel(model);
                        tableWidget = QTableWidget();
                        tableWidget->setSourceModel(identityModel);
                        

                        ?

                        1 Reply Last reply
                        0
                        • VRoninV Offline
                          VRoninV Offline
                          VRonin
                          wrote on last edited by VRonin
                          #14
                          QAbstractItemModel* model = new QStandardItemProxyModel(/*parent*/);
                          QTableView* tableView = new QTableView(/*parent*/);
                          QAbstractProxyModel* identityModel = new QIdentityModel(/*parent*/);
                          identityModel->setSourceModel(model);
                          tableView->setModel(identityModel);
                          

                          "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                          ~Napoleon Bonaparte

                          On a crusade to banish setIndexWidget() from the holy land of Qt

                          1 Reply Last reply
                          2

                          • Login

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