Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-89737

Document QCOMPARE "toString()" with QList<MyCustomItem>

    XMLWordPrintable

Details

    • All
    • fca3ea040c9d05f112c6fc018f0c8e8c68892642 (qt/qtbase/dev) 53471c16eccbc5163c51292bd833cd3e02e934b0 (qt/qtbase/6.0)

    Description

      Hello, I hope I am not missing something obvious here, but it seems the QCOMPARE toString() behaviour has changed a bit for QListful of custom items, and specializing the custom list toString() does not seem to work anymore (fine as such, see below)

      To make it work, it seems one needs to implement the template specialization version of the toString() function for the individual element.  The somewhat confusing bit is that the documentation currently discourages this way for things beyond Qt 5.5+, but for QList of custom items that seems the only way? Unless I am missing something of course.

      As such this seems fine to me (more convenient), but if this is indeed the intended behaviour , perhaps it should be documented into the https://doc-snapshots.qt.io/qt6-dev/qtest.html#toString

      Anyway here's a small test code to illustrate it:

      #include <QTest>
      
      class MyClass {
         QString m_name;
      public:
         MyClass(const QString& name) : m_name(name) {}
         bool operator==(const MyClass& other) const { return m_name == other.m_name; }
         QString name() const { return m_name; }
      };
      using MyClassList = QList<MyClass>;
      
      // called for single element comparison
      char* toString(const MyClass& mc) { return QTest::toString(mc.name()); }
      
      namespace QTest {
      // called for element comparison in QList. Without this prints "<null>"
      template<> char* toString(const MyClass& mc) { return QTest::toString(mc.name()); }
      }
      
      class SimpleTest : public QObject
      {
         Q_OBJECT
      private slots:
         void tst_case_single_element() {
             MyClass A{"A"},B{"B"};
             QCOMPARE(A,B);
         }
         void tst_case_list_element() {
             MyClassList list_1{{"A"},{"B"}};
             MyClassList list_2{{"A"},{"C"}};
             QCOMPARE(list_1, list_2);
         }
      };
      
      QTEST_MAIN(SimpleTest)
      #include "main.moc"
      

      Attachments

        For Gerrit Dashboard: QTBUG-89737
        # Subject Branch Project Status CR V

        Activity

          People

            kleint Friedemann Kleint
            vuokko Juha Vuolle
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes