问题
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