【问题标题】:QTreeView / QFileSystemModel set header labelsQTreeView / QFileSystemModel 设置标题标签
【发布时间】:2012-11-15 20:34:12
【问题描述】:

相当简单的任务,但我没有设法在文档中找到任何有用的东西。我希望 QTreeView 包含一个名为“文件”的列,其中包含来自 QFileSystemView 的数据。这是我得到的:

    QFileSystemModel *projectFiles = new QFileSystemModel();
    projectFiles->setRootPath(QDir::currentPath());
    ui->filesTree->setModel(projectFiles);
    ui->filesTree->setRootIndex(projectFiles->index(QDir::currentPath()));

    // hide all but first column
    for (int i = 3; i > 0; --i)
    {
        ui->filesTree->hideColumn(i);
    }

这给了我一个带有“名称”标题的单列。如何重命名此标头?

【问题讨论】:

    标签: c++ qt qtreeview qfilesystemmodel


    【解决方案1】:

    QAbstractItemModel::setHeaderData() 应该可以工作。如果没有,您始终可以从QFileSystemModel 继承并覆盖headerData()。

    【讨论】:

    • 我也试过了(使用setHeaderData()),但没有成功。查找源src/gui/dialogs/qfilesystemmodel.cpp - 标头在那里硬编码:(因此,子类化QFileSystemModel 并覆盖headerData() 是正确的解决方案。
    【解决方案2】:

    快速但有点肮脏的技巧(请注意w.hideColumn()):

    #include <QApplication>
    
    #include <QFileSystemModel>
    #include <QTreeView>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QTreeView w;
    
        QFileSystemModel m;
        m.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        m.setRootPath("C:\\");
    
        w.setModel(&m);
        w.setRootIndex(m.index(m.rootPath()));
        w.hideColumn(3);
        w.hideColumn(2);
        w.hideColumn(1);
    
        w.show();
    
        return a.exec();
    }
    

    【讨论】:

      【解决方案3】:

      您可以继承 QFileSystemModel 并覆盖方法 headerData()。例如,如果您只想更改第一个标题标签并将其余部分保留其原始值,您可以这样做:

      QVariant MyFileSystemModel::headerData(int section, Qt::Orientation orientation, int role) const {
      
          if ((section == 0) && (role == Qt::DisplayRole)) {
              return "Folder";
          } else {
              return QFileSystemModel::headerData(section,orientation,role);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多