Qt World Summit: Submit your Presentation

How to update QComboBox?

  • Hi,
    I have following typedef with name FT_DEVICE_LIST_INFO_NODE:

    	typedef struct _ft_device_list_info_node {
    		ULONG Flags;
    		ULONG Type;
    		ULONG ID;
    		DWORD LocId;
    		char SerialNumber[16];
    		char Description[64];
    		FT_HANDLE ftHandle;

    I have a vector of this type and this vector is updated every 500ms:

    std::vector<FT_DEVICE_LIST_INFO_NODE> list

    I want to update every 500 ms a QComboBox on GUI. But first I have to check whether or not combobox contains the same values.

    The following code is called every 500ms but it doesn't work as expected. It adds an element more than one every 500ms. Combobox is getting bigger and bigger with same values:

    void MainWindow::on_UpdateDeviceInfos(std::vector<FT_DEVICE_LIST_INFO_NODE> list)
        int nrOfDevices = list.size();
        int nrOfcomboBoxItems = ui->comboBoxDevices->count();
        QVector<DWORD> locIDs;
        for (int index = 0; index < nrOfcomboBoxItems; index++)
            ui->comboBoxDevices->addItem(QString("Device %1 (%2) - %3").arg(0).arg(QString(list[0].Description)).arg(list[0].LocId));
        foreach( DWORD locID , locIDs)
            auto it = std::find_if(list.begin(), list.end(), [locID](const FT_DEVICE_LIST_INFO_NODE & item) { return item.LocId == locID; });
            if (it != end(list))
                ui->comboBoxDevices->addItem(QString("Device %1 (%2) - %3").arg(0).arg(QString(it->Description)).arg(it->LocId));

    How can I make it "correctly"?

  • You can make use of QTimer for that. Just make usage of signals and slots and you are good to go.

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));

    From then on, the update() slot is called every second.


  • It seems that you want to add the item in the list to the comboBoxDevice if there is no such item.

    But what you did is to find is there an item in the list has the same locid as the item in the comboBoxDevice,
    and if it is, you add the item which has the same locid to the comboBoxDevice.

    I think the foreach should be written like this

    foreach( const FT_DEVICE_LIST_INFO_NODE &node, list )
        auto it = std::find_if( locIDs.begin(), locIDs.end(), [&]( const DWORD &item ) { return item == node.LocId; } );
        if ( it == end( locIDs ) )
            ui->comboBoxDevices->addItem(QString("Device %1 (%2) - %3").arg(0).arg(QString(node->Description)).arg(node->LocId));

Log in to reply