0

我尝试在我的 QTableWidget 中修改我的 QHeaderView (Horizo​​ntal) 的文本。

第一个问题:是否可以像 QTableWidgetItem 一样将其设置为可编辑?

第二个问题:如果不可能,我该怎么做,我试着像这样重新粉刷它:

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]);
}

但是标题索引画在我的文字后面。


我尝试的另一个解决方案是:

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);
}

但这不起作用...

我希望有人有解决方案。

谢谢 !

4

2 回答 2

4

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.

于 2014-11-03T17:52:29.100 回答
3

我不知道为什么您的解决方案不起作用,但我找到了一个非常简单的解决方法:

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

谢谢您的帮助 !

于 2014-11-04T13:32:07.160 回答