KM
Katty Misik07 жовтня 2020 р. 01: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

Коментарі

Only authorized users can post comments.
Please, Log in or Sign up
sf

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

  • Результат:90бали,
  • Рейтинг балів8
МВ

Qt - Тест 001. Сигналы и слоты

  • Результат:68бали,
  • Рейтинг балів-1
ЛС

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

  • Результат:53бали,
  • Рейтинг балів-4
Останні коментарі
A
ALO1ZE19 жовтня 2024 р. 05:19
Читалка файлів fb3 на Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь Максимов05 жовтня 2024 р. 04:51
Django - Урок 064. Як написати розширення для Python Markdown Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas505 липня 2024 р. 08:02
QML - Урок 016. База даних SQLite та робота з нею в QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssr08 лютого 2024 р. 15:43
Qt Linux - Урок 001. Автозапуск програми Qt під Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Анатолий Кононенко04 лютого 2024 р. 22:50
Qt WinAPI - Урок 007. Робота з ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Тепер обговоріть на форумі
J
JacobFib17 жовтня 2024 р. 00:27
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
ИМ
Игорь Максимов03 жовтня 2024 р. 01:05
Реализация навигации по разделам Спасибо Евгений!
JW
Jhon Wick01 жовтня 2024 р. 12:52
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл Гусарев27 вересня 2024 р. 06:09
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
Fynjy22 липня 2024 р. 01:15
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Слідкуйте за нами в соціальних мережах