Как создать анимацию переключения в Qt? - PullRequest
0 голосов
/ 30 сентября 2019

У меня есть такой макет: enter image description here

Требование: Когда я нажимаю кнопку, размер detailText объекта будет увеличен / уменьшен (ОБА СЛУЧАИ) в качестве анимации.

Это мой код:

#include <QPropertyAnimation>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->detailText->setVisible(false);
    connect (ui->button, &QPushButton::clicked, this, &MainWindow::buttonClicked);
}

void MainWindow::buttonClicked()
{
    ui->detailText->setVisible(!ui->detailText->isVisible());
    ui->detailText->isVisible() ? ui->button->setText( "view less" ) : ui->button->setText( "view more" );
    runAnimation();
}

void MainWindow::runAnimation()
{
    QPropertyAnimation *animation = new QPropertyAnimation( ui->detailText, "size" );
    animation->setDuration( 1250 );
    if (ui->detailText->isVisible()) {
        animation->setStartValue( QSize( ui->detailText->width(), 0 ) );
        animation->setEndValue( QSize( ui->detailText->width(), ui->detailText->height() ) );
    }
    else {
        animation->setStartValue( QSize( ui->detailText->width(), ui->detailText->height()  ) );
        animation->setEndValue( QSize( ui->detailText->width(), 0 ) );
    }
    animation->start();
}

С этим кодом есть две проблемы:

  1. Когда detailText невидим, иЯ нажимаю кнопку: все окно внезапно расширяется, а затем появляется анимация для detailText. Мне нужна анимация detailText, которая соответственно увеличивает размер окна. Или, другими словами, увеличение всего окна и анимация detailText синхронизированы.

  2. Анимация происходит только одним способом: когда detailText невидим, я нажимаюКнопка, detailText будет отображаться и есть анимация. Но когда detailText виден, я нажимаю кнопку, detailText скрыт, но без анимации, размер окна внезапно сокращается.

Как мне исправить свой код?

Мой * .ui файл:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QWidget" name="">
    <property name="geometry">
     <rect>
      <x>110</x>
      <y>60</y>
      <width>201</width>
      <height>161</height>
     </rect>
    </property>
    <layout class="QVBoxLayout" name="verticalLayout_2">
     <property name="spacing">
      <number>0</number>
     </property>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QLabel" name="incon">
         <property name="minimumSize">
          <size>
           <width>0</width>
           <height>0</height>
          </size>
         </property>
         <property name="text">
          <string>Icon here</string>
         </property>
        </widget>
       </item>
       <item>
        <layout class="QVBoxLayout" name="verticalLayout">
         <property name="spacing">
          <number>0</number>
         </property>
         <item>
          <widget class="QLineEdit" name="introText">
           <property name="text">
            <string>intro text</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QTextEdit" name="detailText">
           <property name="html">
            <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;detail text. This is the detail text of the intro text.&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;You can see this text when you click onto the button.&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Lorem Ipsum&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Blablabla&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;1234&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;5678&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Hello World&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
           </property>
          </widget>
         </item>
        </layout>
       </item>
      </layout>
     </item>
     <item>
      <widget class="QPushButton" name="button">
       <property name="styleSheet">
        <string notr="true"/>
       </property>
       <property name="text">
        <string>View more</string>
       </property>
      </widget>
     </item>
    </layout>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

1 Ответ

0 голосов
/ 30 сентября 2019

Я думаю, что логика должна быть улучшена. В случае, если ваш ui-> detailText виден, логически он должен выглядеть следующим образом:

animation->setStartValue( QSize( ui->detailText->width(), ui->detailText->height()));
animation->setEndValue( QSize( ui->detailText->width(), 0));

Это может быть потому, что если ваш detailText видим, вы уже скрываете его, вместо того, чтобы пытаться уменьшить его, чтобы стать невидимым,И когда он невидим, вам, вероятно, следует попробовать следующее:

animation->setStartValue( QSize( ui->detailText->width(), 0));
animation->setEndValue( QSize( ui->detailText->width(), ui->detailText->height()));

Другими словами, проблема может заключаться в том, что вы должны изменить размер виджета, который хотите анимировать, в направлении, противоположном тому, которое есть сейчас,И, наконец, было бы очень полезно, если бы вы предоставили файл * .ui для вашего проекта, чтобы мы могли лучше отладить ваш код и посмотреть, как он должен быть исправлен. В настоящее время это немного дикое предположение, поэтому я не могу гарантировать, что оно будет работать для вас.

...