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

QListWidgetItem ctor mangles subclassed objects

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Cannot Reproduce
    • Icon: P2: Important P2: Important
    • 4.6.0
    • 4.5.1, 4.5.2, 4.5.3
    • Widgets: Itemviews
    • None

      I've subclassed QListWidgetItem like this:

      class DutyCodeItem : public QListWidgetItem
      {
      public:
      DutyCodeItem(const VagtkodeDb *kode, QListWidget *parent = 0);
      ~DutyCodeItem();

      virtual bool operator<(const QListWidgetItem &item) const;

      virtual QVariant data(int role) const;

      const VagtkodeDb* getDutyCode() const;

      private:
      const VagtkodeDb *m_dutycode;
      };

      The ctor is implemented like this:

      DutyCodeItem::DutyCodeItem(const VagtkodeDb *dutycode, QListWidget *parent)
      : QListWidgetItem(parent, 1000)
      {
      assert(dutycode != NULL);
      m_dutycode = dutycode;
      }

      If I add a new object to a QListWidget like this:

      new DutyCodeItem(obj, IDLB_DUTY_CODES);

      my subclassed object gets mangled and seems to be reverted to a simple QListWidgetItem. IDLB_DUTY_CODES is a QListWidget, by the way.

      This can be verified in the implementation of operator<():

      bool DutyCodeItem::operator<(const QListWidgetItem &item) const
      {
      QListWidgetItem a = const_cast<QListWidgetItem>(&item);

      DutyCodeItem rhs = dynamic_cast<DutyCodeItem>(a);
      return (m_dutycode < rhs->m_dutycode);
      }

      If the object was inserted using the ctor then the dynamic cast will return a NULL pointer.

      There's a workaround by inserting a new object like this:

      DutyCodeItem *item = new DutyCodeItem(obj, 0);
      IDLB_DUTY_CODES->addItem(item);

      I've found the bug in Qt 4.5.1 and it still seems to be there in subsequent (and probably previous) versions of Qt 4.

      However

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

            vfm Thierry Bastian (closed Nokia identity) (Inactive)
            marcbf Marc-Berco Fuhr
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:

                There are no open Gerrit changes