o
otvertkaMay 17, 2018, 3:58 p.m.

Выводит мусор

Добрый день

Я считываю значение цветов из файла и записываю их в вектор. Вроде все нормально. В выводе программы пишет:

testcolor 0 "#000000" 4278190080 "#000000" // testcolor: index, string, rgb, hex

testcolor 1 "#808080" 4286611584 "#808080"

testcolor 2 "#FFFFFF" 4294967295 "#ffffff"

testcolor 3 "#FF00FF" 4294902015 "#ff00ff"

testcolor 4 "#FF0000" 4294901760 "#ff0000"

testcolor 5 "#800000" 4286578688 "#800000"

testcolor 6 "#FFFF00" 4294967040 "#ffff00"

testcolor 7 "#808000" 4286611456 "#808000"

testcolor 8 "#00FF00" 4278255360 "#00ff00"

testcolor 9 "#008000" 4278222848 "#008000"

testcolor 10 "#00FFFF" 4278255615 "#00ffff"

testcolor 11 "#008080" 4278222976 "#008080"

testcolor 12 "#0000FF" 4278190335 "#0000ff"

testcolor 13 "#000080" 4278190208 "#000080"

QFile fileColor("file_color.txt");
    fileColor.open(QIODevice::ReadOnly);
        for(int i=0; !fileColor.atEnd();i++){
            QString color = fileColor.readLine();
            color.remove("\r\n");
            QColor *colorhex = new QColor(color);
            QString style = "QPushButton{background:"+color+";}";
            palette->colorButton.push_back(colorhex);
             qDebug() << "testcolor "<< i << color << " " << colorRGB << palette->colorButton.at(i)->name();
            palette->colorPushButton.at(i)->setStyleSheet(style);
            delete colorhex;
    }
        qDebug() << "testcolor2 " << palette->colorButton.at(2)->name();
Но при выходе из цикла в векторе почему-то хранится мусор. Должно быть "#ffffff". А выводит:

testcolor2 "#000000". Иногда ещё "#dcdcdc"
Спасибо.
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

5
Evgenii Legotckoi
  • May 17, 2018, 4:37 p.m.
  • (edited)

Добрый день!

Вот это лишняя строка

delete colorhex;
Вы сохраняете в куче объект, добавляете его в вектор, и сразу удаляете. В векторе будет невалидный указатель на объект QColor, по идее программа вообще должна крашится.
    o
    • May 18, 2018, 11:57 a.m.

    Спасибо.

    Еще один вопрос.  Вот написал механизм для обработки нажатия мышкой на кнопку.
    ...
    connect(palette->colorPushButton.at(0),&QPushButton::clicked,this, &Paint::slotButton0);
    ...
    connect(this,&Paint::signalFromButton, scene, &paintScene::slotColorPenFromPalette);
    ...

    void Paint::slotButton0()
    {
        emit signalFromButton(*palette->colorButton.at(0));
    }
    void paintScene::slotColorPenFromPalette(QColor color)
    {
          mainPen->colorPen = color;  
    }
    
    Как определить какая кнопка(левая или правая) была нажата?
      Evgenii Legotckoi
      • May 18, 2018, 2:15 p.m.

      Левая или правая кнопка чего? мыши?

      Если мыши, то наследуйтесь от QPushButton и переопределяйте один из методов обработки событий мыший, вот например так
      void MyCustomPushButton::mousePressEvent(QMouseEvent *event)
      {
          if (event->button() == Qt::RightButton) {
              // Todo Something for Right Button
          }
          else if (event->button() == Qt::LeftButton)
          {
              // Todo something for Left Button
          }
          
          // Вызов метода базового класса
          QPushButton::mousePressEvent(event);
      }
        o
        • May 21, 2018, 12:18 p.m.

        Да, мыши.

        Т.е. мне надо создать класс-потомок от QPushButton, и там переопределить метод mousePressEvent?
        И как тогда у  Buttons поменять класс на созданный?
          Evgenii Legotckoi
          • May 22, 2018, 2:57 a.m.
          • The answer was marked as a solution.

          Имено, класс-потомок.
          Если добавляли кнопки в графическом дизайнере, то нужно вызвать контекстное меню на кнопке в дизайнере, выбрать пункт "преобразовать в" либо "Promote to". Там будет диалог, в котором Вам нужно будет добавить ваш насоедованный класс и указать его заголовочный файл и файл реализации.

            Comments

            Only authorized users can post comments.
            Please, Log in or Sign up
            d
            • dsfs
            • April 26, 2024, 2:56 p.m.

            C ++ - Test 004. Pointers, Arrays and Loops

            • Result:80points,
            • Rating points4
            d
            • dsfs
            • April 26, 2024, 2:45 p.m.

            C++ - Test 002. Constants

            • Result:50points,
            • Rating points-4
            d
            • dsfs
            • April 26, 2024, 2:35 p.m.

            C++ - Test 001. The first program and data types

            • Result:73points,
            • Rating points1
            Last comments
            k
            kmssrFeb. 9, 2024, 5:43 a.m.
            Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
            Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
            EVA
            EVADec. 25, 2023, 9:30 p.m.
            Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
            J
            JonnyJoDec. 25, 2023, 7:38 p.m.
            Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
            G
            GvozdikDec. 19, 2023, 8:01 a.m.
            Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
            Now discuss on the forum
            G
            GarApril 22, 2024, 3:46 p.m.
            Clipboard Как скопировать окно целиком в clipb?
            DA
            Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
            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_vlasovApril 14, 2024, 4:41 p.m.
            Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
            Павел Дорофеев
            Павел ДорофеевApril 14, 2024, 12:35 p.m.
            QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
            f
            fastrexApril 4, 2024, 2:47 p.m.
            Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

            Follow us in social networks