0

I try to modify the text of my QHeaderView (Horizontal) in my QTableWidget.

First question: Is it possible to set it editable like a QTableWidgetItem ?

Second question: If it's not possible, how can I do that, I tried to repaint it like this:

void EditableHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();

    painter->setPen(Qt::SolidLine);
    painter->drawText(rect, Qt::AlignCenter, m_sValues[logicalIndex]);
}

But the header index is painted behind my text.


Another solution that I tried is:

void EditableHeaderView::mySectionDoubleClicked( int section )
{
    if (section != -1) // Not on a section
        m_sValues[section] = QInputDialog::getText(this, tr("Enter a value"), tr("Enter a value"), QLineEdit::Normal, "");

    QAbstractItemModel* model = this->model();
    model->setHeaderData(section, this->orientation(), m_sValues[section]);
    this->setModel(model);
}

But that doesn't works...

I hope someone have a solution.

Thank you !

Slot
  • 1,006
  • 2
  • 13
  • 27

2 Answers2

3

It can be done without subclassing, also you don't need paint your section to set text, do this with setHeaderData. For example next code works without errors.

//somewhere in constructor for example
connect(ui->tableWidget->horizontalHeader(),&QHeaderView::sectionDoubleClicked,[=]( int logicalIndex) {//with lambda
    qDebug() << "works";
    QString txt =  QInputDialog::getText(this, tr("Enter a value"), tr("Enter a value"), QLineEdit::Normal, "");
    ui->tableWidget->model()->setHeaderData(logicalIndex,Qt::Horizontal,txt);
});

Before:

enter image description here

After:

enter image description here

I used here C++11 (CONFIG += c++11 to .pro file) and new syntax of signals and slots, but of course you can use old syntax if you want.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • Thank you for your answer ! The qDebug() works but my header text stay the same, I have copy paste your code and I don't understand why it doesn't works :'( – Slot Nov 04 '14 at 08:42
3

I don't know why your solution doesn't works but I found a very simple workaround:

QString res =  QInputDialog::getText(this, tr("Enter a value"), tr("Enter a value"), QLineEdit::Normal, "");
setHorizontalHeaderItem(logicalIndex, new QTableWidgetItem(res));

Thank you for your help !

Slot
  • 1,006
  • 2
  • 13
  • 27
  • It is good that you found and shared answer, +1 for you. I didn't use this in my answer earlier because this will not work with QTableView, I wanted be more general, but it is good that this solution is suitable for you. Good luck :) – Jablonski Nov 04 '14 at 14:01