在QML视图中的Foreach委托

时间:2015-03-29 13:17:45

标签: qt qml qtquick2

是否可以使用ListView或类似功能迭代GridViewforeach的代表?

2 个答案:

答案 0 :(得分:5)

虽然Simon的回答是最佳做法,但为了回答被问到的实际问题,您需要迭代children ListView contentItem之类的ListView { id: list model: mymodel delegate: Text { objectName: "text" text: name + ": " + number } } for(var child in list.contentItem.children) { console.log(list.contentItem.children[child].objectName) } 这样:

const
  NOTIFY_FOR_ALL_SESSIONS = 1;
  {$EXTERNALSYM NOTIFY_FOR_ALL_SESSIONS}
  NOTIFY_FOR_THIS_SESSION = 0;
  {$EXTERNALSYM NOTIFY_FOR_THIS_SESSION}

type

TfrmAlisson = class(TForm)
  lbl2: TLabel;
  procedure FormCreate(Sender: TObject);
  procedure FormDestroy(Sender: TObject);
public
  FLockedCount: Integer;
  procedure WndProc(var Message: TMessage); override;
  function WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool; stdcall;
  function WTSUnRegisterSessionNotification(hWND: HWND): bool; stdcall;
end;

implementation

uses
  // my impl uses here

procedure TfrmAlisson.FormCreate(Sender: TObject);
begin
  if (WTSRegisterSessionNotification(Handle, NOTIFY_FOR_THIS_SESSION)) then
    ShowMessage('Nice')
  else
  begin
    lastError := GetLastError;
    ShowMessage(SysErrorMessage(lastError));
  end;
end;

procedure TfrmAlisson.FormDestroy(Sender: TObject);
begin
  WTSUnRegisterSessionNotification(Handle);
end;

procedure TfrmAlisson.WndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_WTSSESSION_CHANGE:
      begin
        if Message.wParam = WTS_SESSION_LOCK then
        begin
          Inc(FLockedCount);
        end;
        if Message.wParam = WTS_SESSION_UNLOCK then
        begin
          lbl2.Caption := 'Session was locked ' +
          IntToStr(FLockedCount) + ' times.';
        end;
      end;
  end;
  inherited;
end;

function TfrmAlisson.WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool;
  external 'wtsapi32.dll' Name 'WTSRegisterSessionNotification';

function TfrmAlisson.WTSUnRegisterSessionNotification(hWND: HWND): bool;
  external 'wtsapi32.dll' Name 'WTSUnRegisterSessionNotification';

然后,您可以使用objectName或委托项的任何其他属性进行过滤。

答案 1 :(得分:2)

您确定要迭代代表吗?在大多数情况下,您希望迭代模型,因为在ListView的情况下,即使您的模型有100个条目,也可能只有少数代表。这是因为委托在移出可见区域时会被重新填充。

您需要一个具有类似at()函数的模型,它返回给定位置的模型元素。比你可以做的更像

ListView {
    // ...

    function find(convId)
    {
        // count is a property of ListView that returns the number of elements
        if (count > 0)
        {
            for (var i = 0; i < count; ++i)
            {
                // `model` is a property of ListView too
                // it must have an at() metghod (or similar)
                if (model.at(i)["id_"] === convId)
                {
                    return i;
                }
            }
        }
    }

    // ...
}