我正在编写一个程序,需要在Form_Create
事件中,填充名为FileList
的TListView
控件。我想要填充的目录是编译后程序所在目录下的\Files
文件夹。由于我从未使用过TListView
控件,因此想知道如何实现这个功能?
你的问题有多个部分,我会在这里提供一个概述。如果你需要任何特定步骤的帮助,请发布更具体的跟进问题。
确定“编译后程序所在位置”是什么意思。
要获取EXE文件的完整路径,请调用ParamStr(0)
。为了从该字符串中删除EXE文件名,使你只有目录部分,请调用ExtractFilePath
。确保它以反斜杠结尾(使用IncludeTrailingPathDelimiter
),然后附加你的“Files”目录。
获取文件列表。
使用FindFirst
和FindNext
来创建循环,查看所有文件。名称将包括"."和".."相对目录名称,因此您可能希望将它们排除在外。请注意,文件未按任何特定顺序枚举。例如,如果您需要按字母顺序排序,您将需要自己执行排序。(它们在测试中可能看起来按字母顺序排列,但这并不总是正确的。)
var
Rec: TSearchRec;
begin
if FindFirst(path + '\*', faAnyFile, Rec) = 0 then try
repeat
if (Rec.Name = '.') or (Rec.Name = '..') then
continue;
if (Rec.Attr and faVolumeID) = faVolumeID then
continue; // nothing useful to do with volume IDs
if (Rec.Attr and faHidden) = faHidden then
continue; // honor the OS "hidden" setting
if (Rec.Attr and faDirectory) = faDirectory then
; // This is a directory. Might want to do something special.
DoSomethingWithFile(Rec.Name);
until FindNext(Rec) <> 0;
finally
SysUtils.FindClose(Rec);
end;
end;
在控件中添加节点以表示文件。
你可能希望在上面提到的假设的DoSomethingWithFile
函数中执行此操作。使用列表视图的Items
属性执行与项目相关的操作,例如添加新项目。
var
Item: TListItem;
begin
Item := ListView.Items.Add;
Item.Caption := FileName;
end;
TListItem
有其他属性,请查看文档以获取详细信息。如果您在“报表”模式下显示列表视图并且单个节点有多列,则SubItems
属性非常有用。
将图像与项目关联。
列表视图中节点的图像来自相关联的图像列表,LargeImages
和SmallImages
。它们指向窗体上一个或多个TImageList
组件。将图片放在其中,然后将项目的ImageIndex
属性分配给相应的数字。
根据您程序的复杂程度,您可能希望使用Delphi的TShellListView
控件而不是自己完成所有上述工作。
procedure TForm2.Button1Click(Sender: TObject);
var li:TListItem;
SR: TSearchRec;
begin
FileList.Items.BeginUpdate;
try
FileList.Items.Clear;
FindFirst(ExtractFilePath(Application.ExeName) +'*.*', faAnyFile, SR);
try
repeat
li := FileList.Items.Add;
li.Caption := SR.Name;
if ((SR.Attr and faDirectory) <> 0) then li.ImageIndex := 1
else li.ImageIndex := 0;
until (FindNext(SR) <> 0);
finally
FindClose(SR);
end;
finally
FileList.Items.EndUpdate;
end;
end;
您可以通过为不同的文件类型添加不同的图像到TImageList中,并使用ExtractFileExt(SR.Name)来获取文件扩展名,从而进一步构建此功能。
if ((SR.Attr and faDirectory) <> 0) then li.ImageIndex := 1
else if lowercase(ExtractFileExt(SR.Name)) = '.png' then li.ImageIndex := 2
else if lowercase(ExtractFileExt(SR.Name)) = '.pdf' then li.ImageIndex := 3
else li.ImageIndex := 0;
在绘制行时,您需要显示图像。
这应该给你一个想法: http://www.delphidabbler.com/articles?article=16 http://delphi.about.com/od/delphitips2008/qt/lv_checkbox_bmp.htm
唯一的区别是您将绘制一个图标/图像。 在这里,您可以学习如何在网格中实现它:http://delphi.about.com/library/weekly/aa032205a.htm 因此,从两者中您都可以得到想法。