1. 程式人生 > >自定義檔案(夾)選擇對話方塊

自定義檔案(夾)選擇對話方塊

       在QT程式設計中,客製化介面是一個很普遍的需求,畢竟QT在這方面確實很強大,作為常用的檔案(夾)選擇對話方塊,客製化在所難免。下面就詳細介紹下,如何以最簡單的方式客製化。

        對於檔案(夾)對話方塊的客製化,我採用的是將QFileDialog作為子控制元件嵌入到一個QDialog中的方式,這種方式下,不需要自己去實現複雜的控制、排序等邏輯,只要對嵌入的QFileDialog控制元件進行一些屬性的設定,即可滿足我們的基本需要。

下圖為本人實現的效果圖:


1、如何將QFileDialog嵌入QDialog中,請看如下程式碼:

 QFileDialog* fileDlg = new QFileDialog;

 fileDlg->setOption(QFileDialog::DontUseNativeDialog,true);

2、客製化QFileDialog中的子控制元件

        相信大家採用上述方式嵌入後,會發現QFileDialog本身帶的控制元件在顯示方面還是不盡如人意,無法和我們的整體GUI風格進行匹配,那麼下面介紹如何客製化QTreeView和QListView這兩個顯示檔案(夾)的控制元件。直接上程式碼:

QTreeView*dlgTree=fileDlg->findChild<QTreeView*>();
if(dlgTree)
{
dlgTree->header()->setSectionResizeMode(0
,QHeaderView::Stretch);
dlgTree->header()->setSectionResizeMode(2,QHeaderView::ResizeToContents);
dlgTree->header()->setSectionResizeMode(3,QHeaderView::ResizeToContents);
dlgTree->setFocusPolicy(Qt::NoFocus);
dlgTree->setEditTriggers(QAbstractItemView::NoEditTriggers);
dlgTree->setContextMenuPolicy(Qt
::NoContextMenu);
}
QListView*listView=fileDlg->findChild<QListView*>();
if(listView)
{
listView->setFocusPolicy(Qt::NoFocus);
listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
listView->setContextMenuPolicy(Qt::NoContextMenu);
}
QLineEdit*editFileName=fileDlg->findChild<QLineEdit*>();
if(editFileName)
{
editFileName->setText(strFile);
}
        QTreeView就是DetailsView模式下,顯示檔案或者資料夾的容器控制元件,QListView則是ListView模式下,顯示檔案或者資料夾的容器控制元件。而QLineEdit則是選擇檔案時,顯示選中檔名的控制元件

3.隱藏被過濾掉的檔案(夾)

        大家可以發現我的圖片中,僅僅顯示了一個檔案,其它檔案時隱藏的,那是如何實現的呢,採用代理!一般來說,當按照上述步驟完成,並設定了filter後,被過濾掉的項會以灰化的形式顯示在介面上,這個很不美觀,因此我們要想辦法將其隱藏。通過度娘我找到了一個方法,那就是通過自定義一個繼承自QSortFilterProxyModel的子類,並重寫其filterAcceptRows方法,將不顯示的項隱藏起來,下面為實現程式碼:

標頭檔案:

#ifndefFILTERPROXYMODEL_H
#defineFILTERPROXYMODEL_H
#include<QSortFilterProxyModel>
classFilterProxyModel:publicQSortFilterProxyModel
{
Q_OBJECT
public:
protected:
virtualboolfilterAcceptsRow(intsource_row,constQModelIndex&source_parent)constoverride;
signals:
publicslots:
};
#endif//FILTERPROXYMODEL_H

cpp檔案:
#include"filterproxymodel.h"
#include<QFileSystemModel>
boolFilterProxyModel::filterAcceptsRow(intsourceRow,constQModelIndex&sourceParent)const
{
QModelIndexindex0=sourceModel()->index(sourceRow,0,sourceParent);
QFileSystemModel*fileModel=qobject_cast<QFileSystemModel*>(sourceModel());
if(fileModel!=NULL)
{
returnfileModel->flags(index0)&Qt::ItemIsEnabled;
}
else
returnfalse;
}

在客製化的filedialog中,對QFileDialog物件做如下設定:
FilterProxyModel*filterModel=newFilterProxyModel;
fileDlg->setProxyModel(filterModel);
4.其它客製化項
4.1QFileDialog對話方塊右下角的sizeGrid
QFIleDialog被當做子控制元件嵌入後,右下角會有一個區域可拖動來改變對話方塊大小,這個也會影響我們的GUI美化,因此有必要隱藏它:
fileDlg->setSizeGripEnabled(false);
至此,QFileDialog的客製化基本完成。