Qt:按属性在列表中查找对象 [英] Qt : Find object in list by property
本文介绍了Qt:按属性在列表中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Qt的初学者,我更习惯于C#编程.所以我的问题是如何在Qt中实现以下C#代码:
i'm a beginner in Qt, I'm more used to programming in C#. So my question is how to implement in Qt the C# code bellow:
public class MyObject
{
private string myproperty;
public string Myproperty
{
get { return myproperty; }
set { myproperty = value; }
}
}
private void button1_Click(object sender, EventArgs e)
{
List<MyObject> myobjectlist = new List<MyObject>();
MyObject selectedobject = myobjectlist.Find(p => p.Myproperty == "Some name");
}
在Qt中是否可以像上面的代码那样从列表中检索对象?
is it possible in Qt retrieve a object from list like the code above?
推荐答案
这与Qt本身无关.如果可以使用C ++ 11,请使用lambda,就像在C#中一样:
This has little to do with Qt itself. If you can use C++11, use a lambda, just like in C#:
auto itObj = std::find_if(
myobjectlist.begin(), myobjectlist.end(),
[](MyObject o) { return o.myproperty() == "Some name"; }
);
if (itObj != myobjectlist.end())
{
// object was found, use *itObj (or itObj->) to access it/its members
}
else
{
// object was not found
}
在没有C ++ 11的情况下,您必须使用operator()
手工创建一个类用作谓词,或者手动编写一个for
循环.
Without C++11, you'd have to hand-create a class with operator()
to use as the predicate, or write a for
loop by hand.
这篇关于Qt:按属性在列表中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文