QTableWidget spaces between columns



  • For a question of ergonomy, i want to add a space between 2 columns of my QTableWidget. I couldn't find a way in the doc.
    And adding an empty column makes things pretty ugly.

    Is this add possible?

    Thanks



  • In order to get the spacing between the columns in the header, then you can set a stylesheet like the following:

    @setStyleSheet("QHeaderView::section:horizontal {margin-right: 2; border: 1px solid}");@

    To get the spacing between the cells, you can subclass your view, call setShowGrid(false), iterate over its columns and rows and draw the grid yourself with the size you need. The example below illustrates this approach:

    @#include <QtGui>

    class TableWidget : public QTableWidget
    {
    Q_OBJECT
    public:
    TableWidget()
    {
    setRowCount(10);
    setColumnCount(5);
    QTableWidgetItem *newItem = new QTableWidgetItem("An item");
    setItem(0,0, newItem);
    setStyleSheet("QHeaderView::section:horizontal {margin-right: 2; border: 1px solid}");
    }

    void paintEvent(QPaintEvent *event)
    {
        QTableWidget::paintEvent(event);
        QPainter painter(viewport());
        int myHeight = horizontalHeader()->height();
        int i = 0; 
        for (i = 0; i < columnCount(); i++) {
            int startPos = horizontalHeader()->sectionViewportPosition(i);
            QPoint myFrom = QPoint(startPos, 0);
            QPoint myTo = QPoint(startPos, height());
            painter.drawLine(myFrom, myTo);
            startPos += horizontalHeader()->sectionSize(i) - 3;
            myFrom = QPoint(startPos, 0);
            myTo = QPoint(startPos, height());
            painter.drawLine(myFrom, myTo);
        }
        for (i = 0; i < rowCount(); i++) { 
            int startPos = verticalHeader()->sectionViewportPosition(i);
            QPoint myFrom = QPoint(0, startPos);
            QPoint myTo = QPoint(width(), startPos);
            painter.drawLine(myFrom, myTo);
            startPos += verticalHeader()->sectionSize(i);
            myFrom = QPoint(0, startPos);
            myTo = QPoint(width(), startPos);
            painter.drawLine(myFrom, myTo);
        }
    }
    

    };

    #include "main.moc"

    int main(int argc, char** argv)
    {
    QApplication app(argc, argv);
    TableWidget table;
    table.setShowGrid(false);
    table.show();
    return app.exec();
    }
    @



  • Very usefull
    Thank you


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.