【问题标题】:How can I truncate the selected text in a delphi combobox?如何在 delphi 组合框中截断选定的文本?
【发布时间】:2013-07-05 22:16:44
【问题描述】:

我有一个样式设置为 csDropDown 的组合框。我正在尝试在 OnSelect 事件处理程序中执行此操作;

if cboEndTime.ItemIndex > -1 then
  cboEndTime.Text := AnsiLeftStr(cboEndTime.Text, 5);

但它没有效果。

组合项如下所示;

09:00(0 分钟)
09:30(30分钟)
10:00(1 小时)
10:30(1.5 小时)
...

例如,如果我选择第二个项目,我希望组合框的文本显示 09:30,即截断。这会将 ItemIndex 设置为 -1。

我怎样才能做到这一点?

【问题讨论】:

  • 没错,就是csDropDown。为什么这是不可能的?我可以从其他代码中设置文本并输入我喜欢的任何内容。如果是 csDropDownList 我可以理解,但不是。

标签: delphi combobox


【解决方案1】:

看起来您在OnSelect 事件期间对Text 所做的更改随后会被框架覆盖。无论是 Windows API 还是 VCL,我都没有调查过。

一种解决方案是将实际更改推迟到原始输入事件的处理完成为止。像这样:

const
  WM_COMBOSELECTIONCHANGED = WM_USER;

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    procedure ComboBox1Select(Sender: TObject);
  protected
    procedure WMComboSelectionChanged(var Msg: TMessage); message WM_COMBOSELECTIONCHANGED;
  end;

implementation

{$R *.dfm}

procedure TForm1.ComboBox1Select(Sender: TObject);
begin
  PostMessage(Handle, WM_COMBOSELECTIONCHANGED, 0, 0);
end;

procedure TForm1.WMComboSelectionChanged(var Msg: TMessage);
begin
  if ComboBox1.ItemIndex<>-1 then
  begin
    ComboBox1.Text := Copy(ComboBox1.Text, 1, 1);
    ComboBox1.SelectAll;
  end;
end;

【讨论】:

    【解决方案2】:

    您可以将样式设置为 OwnerDrawFixed 并自行使用 OnDrawItem 绘制所需的文本。 此示例中的查找将显示所有内容,仅选择修剪后的字符串。

    procedure TForm3.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    
      var
       C:TComboBox;
    
      Function Strip(const s:String):String;
        begin
           if C.DroppedDown then result := s
           else Result := Copy(s,1,pos('(',s)-1);
        end;
    begin
         C := TComboBox(Control);
         C.Canvas.FillRect(Rect);
         C.Canvas.TextOut(Rect.left + 1,Rect.Top + 1, Strip(C.Items[Index] ));
    end;
    

    【讨论】:

    • 如果我所有者绘制控件,底层值是否仍然不正确?更糟糕的是与视觉上显示的不一致。这不会让编辑文本变得非常困难吗?
    • 没错,我将to show 09:30 解释为只是显示值已更改,而不是更改它。如果您只想使用 9:30,而不是直接访问 Text,您可以通过 Stripped(Combobox.Items[Combobox.ItemIndex]) 访问该值,其中 Stripped 将用于上述 Result := 部分 Function Strip 和访问项目。但是看看@DavidHeffernan 的解决方案,它会更适合你。
    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多