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");
}
is it possible in Qt retrieve a object from list like the code above?
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
}
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.
Maybe this way?
void MyClass::button1_Click()
{
QList<MyObject> myobjectlist;
MyObject selectedobject;
foreach (const MyObject &o, myobjectlist) {
if (o.property("Some name").isValid()) {
selectedobject = o;
break;
}
}
}
Assuming that the MyObject
is a QObject
.
Add to .pro file CONFIG +=c++11
#include <QString>
#include <QList>
#include <algorithm>
//...
//...
class MyObject
{
private:
QString myproperty;
public:
void MypropertySet(QString s)
{
myproperty=s;
}
QString MypropertyGet() const
{
return myproperty;
}
};
void MainWindow::on_pushButton_clicked()
{
QList<MyObject> myobjectlist;
MyObject selectedobject=*std::find_if(myobjectlist.begin(), myobjectlist.end(),[] (const MyObject& s) { return s.MypropertyGet()=="Some name"; });
}
Main window has a button and when you click it a privete slot from main window is called on_pushButton_clicked(). If you have more questions i can post whole files. If you are not sure that the object you are looking for is in the list then you have to check if you found it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With