Custom QListWidget

From Qt Wiki
Revision as of 10:18, 24 February 2015 by Maintenance script (talk | contribs)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


Custom QListWidget

Small snippet showing how to override dropEvent method on a custom QListWidget.

  1. First create a Qt Gui Application using Qt Creator and add a QListWidget to it.
  2. Create the below given MyListWidget.h and MyListWidget.cpp files.
  3. Right click on the QListWidget created in the Form designer and Promote it to MyListWidget
  4. When you run the application, if you drop something on MyListWidget, you will first see the debug msg (dropEvent of MyListWidget), and then it calls the dropEvent of the QListWidget …

The header file

<br />#ifndef MYLISTWIDGET_H<br />#define MYLISTWIDGET_H

#include &lt;QListWidget&amp;gt;

class MyListWidget : public QListWidget<br />{<br /> Q_OBJECT

public:

MyListWidget(QWidget *parent = 0);

protected:<br /> void dropEvent(QDropEvent *event);<br />};

#endif // MYLISTWIDGET_H<br />

The cpp file

<br />#include &quot;mylistwidget.h&amp;quot;<br />#include &lt;QDebug&amp;gt;

MyListWidget::MyListWidget(QWidget *parent)<br /> : QListWidget(parent)<br />{<br /> setDragDropMode(QAbstractItemView::DragDrop);<br /> setDefaultDropAction(Qt::MoveAction);<br /> setAlternatingRowColors(true);<br />}

void MyListWidget::dropEvent(QDropEvent *event)<br />{<br /> qDebug() &lt;&lt; &quot;This is my custom dropEvent() method!&quot;;<br /> QListWidget::dropEvent(event);<br />}<br />