jeudi 11 mai 2023

Flash an active Qt tree widget item green

I would like to flash (between green & white) an active item in my QTreeWidget in Qt. This means it should stop flashing the previous items that were active once. I have tried the following and not had it working as I want it. Please help.

**void Dialog::slotTestRunUpdate(QString sTestName)
{**
    QHashIterator<QString, QWidget*> hashIt(treeFormHash); //iterator for testnames and test forms// 
    //e.g treeFormHash.insert("Test 1",    pCTest1FormObj);
    treeFormHash.insert("Test 2",    pCTest2FormObj);
    treeFormHash.insert("Test 3",    pCTest3FormObj);
    treeFormHash.insert("Test 4",    pCTest4FormObj);
    treeFormHash.insert("Test 5",    pCTest5FormObj);//

    QTreeWidgetItemIterator treeIt(ui->treeWidget); //iterator for items in QTreeWidget
    //Store a pointer to the last active item
    QTreeWidgetItem* prevItem = nullptr;

    while(*treeIt) //Search for an existing item with the specified text//
    {
        QTreeWidgetItem* item = *treeIt;
        ui->treeWidget->clearSelection();

        if(item->text(0) == sTestName) {
            qDebug() << "treeIt=" << item->text(0) << "\r\n";

            //A timer to flash between green and white//
            QTimer *timer = new QTimer(this); //a timer object

            timer->setInterval(1000); //interval of 1s
            timer->start(); //start timer

            //When the timer times out, it toggles the background color of the active item between green and white.
            //The timer is connected to a lambda function that captures the item variable by value.
            //The lambda function checks the current background color of the item and switches it to the opposite color.
            QObject::connect(timer, &QTimer::timeout, [=]() mutable{
            if (item->background(0).color() == Qt::green) {item->setBackground(0, Qt::white);}
                else { item->setBackground(0, Qt::green); }
            });

            //Stop flashing the last active item
            if ((prevItem != nullptr) && (prevItem != item)) { prevItem->setBackground(0, Qt::white); timer->stop(); delete timer;}

            ui->treeWidget->setCurrentItem(item);
            item->setSelected(true);
            ui->verticalLayout->itemAt(0)->widget()->setVisible(false);
            
            while(hashIt.hasNext()) {
                hashIt.next();
                //qDebug() << "i: " << hashIt.key() << " " << hashIt.value();
                if(hashIt.key() == sTestName) {
                    ui->verticalLayout->insertWidget(0, hashIt.value());
                    ui->verticalLayout->itemAt(0)->widget()->setVisible(true); break;} }

            prevItem = item;
            return;}
        treeIt++;}   
**}**

Aucun commentaire:

Enregistrer un commentaire