Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt : Find object in list by property

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?

like image 627
Rui Sebastião Avatar asked Jun 13 '14 13:06

Rui Sebastião


3 Answers

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.

like image 64
Angew is no longer proud of SO Avatar answered Oct 09 '22 14:10

Angew is no longer proud of SO


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.

like image 24
vahancho Avatar answered Oct 09 '22 13:10

vahancho


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.

like image 22
MarcinG Avatar answered Oct 09 '22 14:10

MarcinG