KM
Katty Misik7 октября 2020 г. 1:50

Как тут сделать мой виджет другим цветом медленно и красиво(возможн при помощи дюрейшн, или любым другим способом)

qt, setDuration, Animation, Widget, ui, label

#include "pinpoint.h"
#include "ui_pinpoint.h"
#include <QPropertyAnimation>
#include <interfaces/fastproxystyle.h>

Connection& PinPoint::getConnection()

{
    return connection;
}

int PinPoint::getId() const
{
    return id;
}

void PinPoint::setId(int value)
{
    id = value;
}

PinPoint::PinPoint(QWidget *parent) :
    QWidget(parent),
    connection(nullptr),
    ui(new Ui::PinPoint),
    notConnected("Punkt", "Blad", Error::Priority::CriticalError, true),

    m_colorAnimation(this, "color"),

    zoneViolation("Alarm", "Naruszenie strefy", Error::Priority::CriticalError, true,true,true,"Sprawdź stan strefy")
{
    ui->setupUi(this);
    this->layout()->setAlignment(ui->label, Qt::AlignCenter);
    connect(ui->pin, &PointShape::mouseOver, this, &PinPoint::mouseOverPin);
    connect(ui->pin, &PointShape::setupDeclared, this, &PinPoint::setupDeclared);
    connect(&connection, &Connection::currentStateUpdated, this, &PinPoint::updateState);
    connect(&connection, &Connection::updateView, this, &PinPoint::updateView);
    connect(&connection.getZonesWidget(), &ZonesListWidget::updateDB, this, &PinPoint::onUpdateEmit);
    this->setStyle(new FastProxyStyle(this->style()));
    connect(ui->pin, &PointShape::mouseOver1, this, &PinPoint::NoWidget);
    // connect(this, &PinPoint::mouseOverPin, this, [ui->pin](){ ui->pin->setStyleSheet("background-color: red;"); });
   // m_colorAnimation(this, "color");


    //connect(ui->pin, &PointShape::mouseOver1, this, &PinPoint::mouseOverPin2);

}

void PinPoint::fillSetup(const QString& address, const QString& name) {
    setIP(address);
    setName(name);
    connection.setConnectionData(getIP(), 7094);
}

void PinPoint::updateState(CustomState *state, QList<Zone*> source){
    if(!source.isEmpty()) {
        if(state==&connection.getZonesWidget().alarm || state==&connection.getZonesWidget().silentAlarm) {
            QString helpString="";
            foreach(auto item, source) {
                helpString+=item->getId()+" ";
            }
            zoneViolation.setSource(this->getText());
            zoneViolation.setValue("Problem w jednostce "+this->getText()+" (IP: "+this->getIP().toString()+"). Wystąpił "+state->getName()+" w strefach: "+helpString);
            generateError(zoneViolation);
        }
        else cancelError(zoneViolation);
    }

    ui->pin->setState(*state);
    refreshHint();
    //TUTAJ DODAC ALARMY
    /*if(ui->pin->state!=_state && (_state == Global::States::ALARM || _state==Global::States::CON_LOST))
        generateError(notConnected);
    else if((ui->pin->state==Global::States::ALARM && _state!=Global::States::ALARM) || (ui->pin->state==Global::States::CON_LOST && _state!=Global::States::CON_LOST))
        cancelError(notConnected);

    ui->pin->setState(_state);*/
}

void PinPoint::updateView(const QHostAddress& address, uint16_t port)
{
    ui->label_2->setText(address.toString());
    Q_UNUSED(port)
}

void PinPoint::onUpdateEmit()
{
    emit(updateDatabase(*this));
}

void PinPoint::copy()

{


}

void PinPoint::setPos(const QPointF &pos) {
    position = pos;
    this->move(Converter::toPointToMiddle(position, size()));
}

bool PinPoint::isFakeElement()
{
    return (getIP().toString()=="0.0.0.0");

}


void PinPoint::SetColor(const QColor& color)
{
    m_currentColor = color;
 //   QString css = "QPushButton { border-radius: 5px; ";
  //  css.append("border: 1.5px solid rgb(91,231,255); ");
    QString strColor = QString("rgb(%1, %2, %3)").arg(color.red()).arg(color.green()).arg(color.blue());
  //  css.append("background-color: " + strColor + "; }");
  //  setStyleSheet(css);
}



const QColor& PinPoint::GetColor() const
{
    return m_currentColor;
}



void PinPoint::mouseOverPin(){
    raise();
    if(!isFakeElement())

    emit mouseOverMe();

    m_colorAnimation.stop();

        m_colorAnimation.setDuration(900);
        m_colorAnimation.setStartValue(GetColor());
        m_colorAnimation.setEndValue(QColor(100, 100, 100));

        m_colorAnimation.setEasingCurve(QEasingCurve::Linear);

        m_colorAnimation.start();


  //  ui->label->setStyleSheet("font-size: 13px;\ncolor: black;\nbackground-color: limegreen ;\npadding: 1px 3px 2px 3px;\nborder-top: 1px solid rgb(20, 19, 50);\nborder-radius: 5px;\nfont-weight:400;  ");
  //  ui->widget->setStyleSheet("border-top-left-radius: 3px;\nborder-top-right-radius: 3px;\nborder-bottom-right-radius: 3px;\nborder-bottom-left-radius: 3px; background-color: black ; ");
 //   ui->label_2->setStyleSheet("color:white;\nfont-size: 11px;\nfont-weight:500;\nbackground:darkgreen;\npadding:1px 3px; ");

}

void PinPoint::NoWidget()
{


    m_colorAnimation.stop();

       m_colorAnimation.setDuration(900);
      m_colorAnimation.setStartValue(GetColor());
      m_colorAnimation.setEndValue(QColor(255, 0, 0));

       m_colorAnimation.setEasingCurve(QEasingCurve::Linear);

       m_colorAnimation.start();

   //StartHoverEnterAnimation();
  //  m_colorAnimation.stop();

    //  m_colorAnimation.setDuration(900); //set your transition
     // m_colorAnimation.setStartValue(GetColor()); //starts from current color
    //  m_colorAnimation.setEndValue(QColor(255, 0, 0));//set your regular color

    //  m_colorAnimation.setEasingCurve(QEasingCurve::Linear);//animation style

     // m_colorAnimation.start();

  //  m_colorAnimation.stop();

     //  m_colorAnimation.setDuration(900); //set your transition
     //  m_colorAnimation.setStartValue(Qt::White); //starts from current color
     //  m_colorAnimation.setEndValue(QColor(100, 100, 100));//set your hover color

     //  m_colorAnimation.setEasingCurve(QEasingCurve::Linear);//animation style

    //   m_colorAnimation.start();

  // ui->label->setStyleSheet("font-size: 13px;\ncolor: rgb(225, 225, 245);\nbackground-color: rgb(31, 34, 68);\npadding: 1px 3px 2px 3px;\nborder-top: 1px solid rgb(20, 19, 50);\nborder-radius: 5px;\nfont-weight:400;  ");
  // ui->widget->setStyleSheet("border-top-left-radius: 3px;\nborder-top-right-radius: 3px;\nborder-bottom-right-radius: 3px;\nborder-bottom-left-radius: 3px; ");
 //  ui->label_2->setStyleSheet("color:white;\nfont-size: 11px;\nfont-weight:500;\nbackground:rgb(34, 34, 34);\npadding:1px 3px; ");

}

void PinPoint::setName(const QString &text)
{
    ui->label->setText(text);
    notConnected.setSource(text);
    notConnected.setValue("Alarm w obiekcie "+text+" (ip:"+getIP().toString()+")!");
}
void PinPoint::refreshHint() {
    this->setToolTip("Nazwa: "+ui->label->text()+"\nIP: "+this->getIP().toString()+"\n"+connection.getZonesWidget().getInfoString());
}
void PinPoint::setIP(const QString& ip)
{
    connection.setCentralAddress(QHostAddress(ip));
    ui->label_2->setText(ip);
    refreshHint();
}

PinPoint::~PinPoint(){delete ui;}
QPointF PinPoint::getPos() {return position;}
QString PinPoint::getText() {return this->ui->label->text();}
QString PinPoint::getStateString(){return ui->pin->getStateString();}
QHostAddress PinPoint::getIP(){return connection.getCentralAddress();}
Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Вам это нравится? Поделитесь в социальных сетях!

0

Комментарии

Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь
SH
  • Sak Hax
  • 25 апреля 2024 г. 21:00

C++ - Тест 001. Первая программа и типы данных

  • Результат:33баллов,
  • Очки рейтинга-10
г
  • ги
  • 23 апреля 2024 г. 22:51

C++ - Тест 005. Структуры и Классы

  • Результат:41баллов,
  • Очки рейтинга-8
l
  • laei
  • 23 апреля 2024 г. 16:19

C++ - Тест 004. Указатели, Массивы и Циклы

  • Результат:10баллов,
  • Очки рейтинга-10
Последние комментарии
k
kmssr9 февраля 2024 г. 2:43
Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Анатолий Кононенко5 февраля 2024 г. 9:50
Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVA25 декабря 2023 г. 18:30
Boost - статическая линковка в CMake проекте под Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJo25 декабря 2023 г. 16:38
Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
Gvozdik19 декабря 2023 г. 5:01
Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Сейчас обсуждают на форуме
G
Gar22 апреля 2024 г. 12:46
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil Academics20 апреля 2024 г. 14:45
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasov14 апреля 2024 г. 13:41
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел Дорофеев14 апреля 2024 г. 9:35
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrex4 апреля 2024 г. 11:47
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Следите за нами в социальных сетях