Change QHeaderView data

可紊 提交于 2019-12-11 20:44:33

问题


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 !


回答1:


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:

After:

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.




回答2:


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 !



来源:https://stackoverflow.com/questions/26719640/change-qheaderview-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!