Russian Qt Forum
Май 12, 2024, 22:23 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1]   Вниз
  Печать  
Автор Тема: Мигание таба  (Прочитано 2456 раз)
opera
Чайник
*
Offline Offline

Сообщений: 93


Просмотр профиля
« : Январь 20, 2021, 11:32 »

Добрый день, пытаюсь реализовать мигание таба в табвиджете, к примеру, если активный там 0, но на другой там пришли какие-то данные и он требует внимания, нашел код в интернете, в принципе не сложный, но не работает так, как хочется, почему-то сама область таба не выделяется цветом, а только линии вдоль левой и нижней рамки.
Код:
#include <QTabWidget>
#include <QTabBar>
#include <QStylePainter>
#include <QStyleOptionTab>
#include <QTimer>




class TabBarAlert : public QTabBar
{
    int indexAlert = -1;
    QColor mColor;
    Q_OBJECT
public:
    TabBarAlert(QWidget *parent = Q_NULLPTR):QTabBar(parent)
    {
        mColor = Qt::red;
    }
    void setIndexAlert(int index)
    {
        if(indexAlert == index)
            return;
        indexAlert = index;
        update();
    }

    int getIndexAlert() const
    {
        return indexAlert;
    }

    QColor getColor() const
    {
        return mColor;
    }
    void setColor(const QColor &color)
    {
        if(color == mColor)
            return;
        mColor = color;
        update();
    }

protected:
    void paintEvent(QPaintEvent *event){

        if(indexAlert> -1 && indexAlert < count())
        {
            QStylePainter painter(this);
            QStyleOptionTab opt;

            for(int i = 0;i < count();i++)
            {
                QString text = tabText(i);
                mColor = Qt::red;
                QString colorName = mColor.name();
                initStyleOption(&opt,i);

                if(indexAlert == i)
                    opt.palette.setColor(QPalette::Button, mColor);
                painter.drawControl(QStyle::CE_TabBarTabShape, opt);
                painter.drawControl(QStyle::CE_TabBarTabLabel,opt);
                //painter.drawControl(QStyle::CE_TabBarTab,opt);



            }
        }
        else
        {
            QTabBar::paintEvent(event);
        }
    }

};

class TabWidgetAlert : public QTabWidget
{
    TabBarAlert *tb;
    QTimer *timer;
    bool on = false;
    int indexAlert = -1;

    Q_OBJECT
public:
    TabWidgetAlert(QWidget *parent = Q_NULLPTR):QTabWidget(parent)
    {
        tb = new TabBarAlert(this);
        setTabBar(tb);
        tb->setColor(Qt::black);


        /*
        *Disable the alert if the current tab matches the alert tab.
        */
        connect(this, &TabWidgetAlert::currentChanged, [this](int index){
            if(index == tb->getIndexAlert()){
                tb->setIndexAlert(-1);
                on = false;
                timer->stop();
           }
        });

        timer = new QTimer(this);

        /*
        *Create the blink
        */
        connect(timer, &QTimer::timeout, [this]()
        {
            tb->setIndexAlert(on? indexAlert: -1);
            on = !on;
        });
    }

    void setAlert(int index)
    {
        indexAlert = index;
        timer->start(500);
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);



    TabWidgetAlert tabs;
        tabs.addTab(new QWidget(),"TAB 1");
        tabs.addTab(new QWidget(),"TAB 2");
        tabs.addTab(new QWidget(),"TAB 3");

        tabs.setAlert(1);

        tabs.show();
        return a.exec();
}




подскажите,может кто сталкивался или знает?спасибо
Записан
tux
Бывалый
*****
Online Online

Сообщений: 400



Просмотр профиля
« Ответ #1 : Январь 20, 2021, 12:22 »

В такой реализации оно от темы оформления будет зависеть. Только что проверил - если включить тему Fusion, то моргает красным. В остальных темах будет моргать только рамка.
А откуда вы взяли оригинальный код?
« Последнее редактирование: Январь 20, 2021, 12:31 от tux » Записан

opera
Чайник
*
Offline Offline

Сообщений: 93


Просмотр профиля
« Ответ #2 : Январь 20, 2021, 12:25 »

https://gist.github.com/eyllanesc/4a821d2956b5e2ee841f3eb156da078d
Записан
opera
Чайник
*
Offline Offline

Сообщений: 93


Просмотр профиля
« Ответ #3 : Январь 20, 2021, 12:26 »

тогда буду добавлять кнопки на табы и работать с ними
Записан
tux
Бывалый
*****
Online Online

Сообщений: 400



Просмотр профиля
« Ответ #4 : Январь 20, 2021, 12:31 »

Лучше исправить. С кнопками на табах совсем костыльно будет. Улыбающийся
Записан

opera
Чайник
*
Offline Offline

Сообщений: 93


Просмотр профиля
« Ответ #5 : Январь 20, 2021, 13:13 »

а какие предложения есть?
Записан
tux
Бывалый
*****
Online Online

Сообщений: 400



Просмотр профиля
« Ответ #6 : Январь 20, 2021, 13:52 »

В вашем случае можно просто подождать. Если я решу эту проблему, то я выложу здесь результат.
Либо самостоятельно решить проблему.
Или просто использовать тему Fusion (мало ли, вдруг она вам нравится). Кстати, проверил - она работает как в win, так и в linux)
« Последнее редактирование: Январь 20, 2021, 20:28 от tux » Записан

opera
Чайник
*
Offline Offline

Сообщений: 93


Просмотр профиля
« Ответ #7 : Январь 20, 2021, 15:32 »

вот что навоял с QPushButton' ами, может кому пригодиться:

HEADER:
Код:
#pragma once
#include <QObject>
#include <QTabWidget>
#include <QPushButton>

class TabModificator :public QObject
{
    Q_OBJECT

public:
    TabModificator(QTabWidget* tabWidget);
    ~TabModificator();
    void addIndexAlert(int index) { _indexAlert.insert(index); }

    void setActivityButton(int index);

    int getCurrentButtonIndex() { return _pushButtonBook.key(_currentButton); }
private:
    QTabWidget* _tabWidget = nullptr;
    QMap<int, QPushButton*> _pushButtonBook;
    QTimer* _timer = nullptr;
    QSet<int> _indexAlert;
    bool _timerValue = false;
    QPushButton* _currentButton = nullptr;
signals:
    void emitButtonHidden(QPushButton* pb, bool sign);
private slots:
    void slotButtonHidden(QPushButton* pb, bool sign);

};


SOURCE:
Код:
#include "TabModificator.h"



TabModificator::TabModificator(QTabWidget* tabWidget): _tabWidget(tabWidget)
{
for (int index = 0; index < _tabWidget->tabBar()->count(); index++)
{
QPushButton* pb = new QPushButton(_tabWidget->tabText(index),_tabWidget);
connect(this, SIGNAL(emitButtonHidden(QPushButton*, bool)), this, SLOT(slotButtonHidden(QPushButton*, bool)));
_pushButtonBook.insert(index, pb);
QRect rectTab = _tabWidget->tabBar()->tabRect(index);
pb->setGeometry(rectTab);
pb->setStyleSheet("QPushButton{background-color: lightgray;border: 0px;}"
"QPushButton:hover{background-color: lightblue;border: 0px;}");
if (index == 0)
{
pb->setHidden(true);
_currentButton = pb;
}
connect(pb, &QPushButton::clicked, [index, this, pb]()
{
_tabWidget->setCurrentIndex(index);
_currentButton = pb;
QMap<int, QPushButton*>::iterator itPushButtonBook = _pushButtonBook.begin();
for (; itPushButtonBook != _pushButtonBook.end(); itPushButtonBook++)
{
emit emitButtonHidden(itPushButtonBook.value(),false);
}
emit emitButtonHidden(pb, true);
_indexAlert.remove(index);
});


_timer = new QTimer(this);
connect(_timer, &QTimer::timeout, [this]()
{
QSet<int>::iterator itIndexAlert = _indexAlert.begin();
for (; itIndexAlert != _indexAlert.end(); itIndexAlert++)
{
if (_timerValue)
_pushButtonBook.value(*itIndexAlert)->setStyleSheet("QPushButton{background-color: red;border: 0px;}");
else
_pushButtonBook.value(*itIndexAlert)->setStyleSheet("QPushButton{background-color: lightgray;border: 0px;}");
_timerValue = !_timerValue;
}
});
_timer->start(500);

}
}
TabModificator::~TabModificator()
{
QMap<int, QPushButton*>::iterator itPushButtonBook = _pushButtonBook.begin();
for (; itPushButtonBook != _pushButtonBook.end(); itPushButtonBook++)
delete itPushButtonBook.value();
delete _timer;
}

void TabModificator::setActivityButton(int index)
{
_pushButtonBook.value(index)->clicked();
}

void TabModificator::slotButtonHidden(QPushButton* pb, bool sign)
{
pb->setHidden(sign);
if (sign)
{
pb->setStyleSheet("QPushButton{background-color: lightgray;border: 0px;}"
"QPushButton:hover{background-color: lightblue;border: 0px;}");
}
}
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.049 секунд. Запросов: 22.