简体   繁体   中英

How do I change the header text of a QTableView?

For instance if the header displayed "ColumnName" in English I have tried to change it to a new language by handling the language change event:

QApplication::instance()->installTranslator( translator );
ui->retranslateUi(this);
ui->tableView->retranslate();

and then calling

model->setHeaderData(0, Qt::Horizontal, tr("ColumnName"), Qt::DisplayRole);
model->headerDataChanged(Qt::Horizontal, 0, 1);

But this does not seem to trigger the view to update. All the other widgets do display in the new language.

In the derived model class I have also overridden the QAbstractTableModel headerData() function:

QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole)
    {
    if (orientation == Qt::Horizontal) {
      switch (section)
      {
      case Priority:
        return tr("ColumnName");
      case FileName:
        return tr("Filename");
      default:
        return QString("");
      }
    }
  }  
  return QVariant();
}

Thank you for the insights. It turns out there was a simple mistake in my derived model header file. The class needs to have the Q_OBJECT macro present for the translation process to work correctly. It now updates the headers correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM