2011-12-04 67 views
2

這是從Qt的教程複製的類:爲什麼我的視圖不顯示標題?

class Window : public QWidget 
{ 
    Q_OBJECT 

public: 
    Window(); 

    void setSourceModel(); 

private slots: 
    void filterRegExpChanged(); 
    void filterColumnChanged(); 
    void sortChanged(); 
    void addMail(); 

private: 
    QSortFilterProxyModel *proxyModel; 
    QStandardItemModel *model; 

    QGroupBox *sourceGroupBox; 
    QGroupBox *proxyGroupBox; 

    QTreeView *sourceView; 
    QTreeView *proxyView; 
    QCheckBox *filterCaseSensitivityCheckBox; 
    QCheckBox *sortCaseSensitivityCheckBox; 
    QLabel *filterPatternLabel; 
    QLabel *filterSyntaxLabel; 
    QLabel *filterColumnLabel; 
    QLineEdit *filterPatternLineEdit; 
    QComboBox *filterSyntaxComboBox; 
    QComboBox *filterColumnComboBox; 
    QPushButton* button; 
}; 

這是一個構造函數的DEF:

Window::Window() 
{ 
    model = new QStandardItemModel(this); 
//HEADERS ARE NOT DISPLAYED EVEN THOUGH I'M SETTING THEM HERE 
    model->setHeaderData(0, Qt::Horizontal, QObject::tr("Subject")); 
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("Sender")); 
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("Date")); 

    proxyModel = new QSortFilterProxyModel; 
    proxyModel->setDynamicSortFilter(true); 

    sourceView = new QTreeView; 
    sourceView->setRootIsDecorated(false); 
    sourceView->setAlternatingRowColors(true); 

    proxyView = new QTreeView; 
    proxyView->setRootIsDecorated(false); 
    proxyView->setAlternatingRowColors(true); 
    proxyView->setModel(proxyModel); 
    proxyView->setSortingEnabled(true); 

connect(button,SIGNAL(clicked()),this,SLOT(addMail()));//THIS SEEMS NOT TO MAKE ANY DIFFERENCE - NOTHING IS ADDED 
}; 

void Window::addMail() 
{ 
    model->insertRow(0); 
    model->setData(model->index(0, 0), "subject"); 
    model->setData(model->index(0, 1), "sender"); 
    model->setData(model->index(0, 2), "date"); 
} 
void Window::setSourceModel() 
{ 
    proxyModel->setSourceModel(model); 
    sourceView->setModel(model); 
} 
int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 
    Window window; 
    window.setSourceModel(); 
    window.show(); 

    return app.exec(); 
} 

經由addMail加入既不頭也不數據被顯示。爲什麼?

回答

-1

如果你看看文檔,你會注意到,setHeaderData有四個參數,最後一個是角色。 該角色默認爲Qt :: EditRole,但您可能需要Qt :: DisplayRole。

+0

監視默認值 – beyrem

4

QAbstractItemModel :: setHeaderData是爲了處理用戶對標題的編輯,而不是以編程方式設置它們。然後模型必須實現setHeaderData來處理這些編輯請求。 QStandardItemModel顯然不會創建標題項目,如果他們最初沒有設置,所以什麼也沒有發生。

當您使用QStandardItemModel時,應該使用setHorizontalHeaderItemsetHorizontalHeaderLabels(垂直變體也可用)來設置標題。