PDA

View Full Version : get a pixmap for a dragged QTreeWidgetItem?



qlands
27th September 2011, 08:44
Hi,

I am dragging a QTreeWidgetItem from one QTreeWidget to another. How can I draw a pixmap with the text (caption) of the dragged item to use it in QDrag?

Thanks,
Carlos.

dennis81
27th September 2011, 08:52
I use this code...

QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
mimeData->setText("Hello World");
drag->setMimeData(mimeData);
drag->setPixmap(yourPixmap);
Qt::DropAction dropAction = drag->start();

qlands
27th September 2011, 10:47
Hi,

I have almost the same code but I want to show which QTreeWidgetItem is dragging hence the pixmap must be created with the caption of the QTreeWidgetItem!

Dennis, you indicated
drag->setPixmap(yourPixmap) but how you create yourPixmap with the caption of the QTreeWidgetItem?

Carlos.

stampede
27th September 2011, 10:56
Can't you use QPainter to draw text on the pixmap, before you pass it to QDrag ?

qlands
27th September 2011, 11:18
I tried that with:



QPixmap pixmap;
QPainter paint(&pixmap);
QFont font;
QFontMetrics met(font);
paint.drawText(met.boundingRect("Some text here"),Qt::AlignLeft,"Some text here");
mimeData = new QMimeData;
mimeData->setData("object/x-IMPACT-plugin", itemData);
mimeData->setText("Some text here");
drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(pixmap);
drag->exec(Qt::MoveAction);


But I still don't get it!

stampede
27th September 2011, 12:07
Well, you are trying to draw on a null pixmap...
Initialize the pixmap with non-zero size, fill it with background color, then draw text.

qlands
27th September 2011, 13:22
ok.

Almost there, now I get a white pixmap with the appropriate size but without the text.



QPixmap pixmap(met.boundingRect("Some text here").size());
pixmap.fill();
QPainter paint(&pixmap);
paint.drawText(met.boundingRect("Some text here"),Qt::AlignLeft,"Some text here");


I reckon painter is not starting to draw in a good position.

Yep! It was the Y... it must be negative



QRectF rect(met.boundingRect("Some text here"));
paint.drawText(0,0-rect.y(),"Some text here");


Thanks for your help.

CodeCat
18th September 2016, 08:33
When you create the QTreeWidgetItem, do not set the text or icon.

Instead, create a QWidget that contains 2 QLabels (one for the icon, one for the text), then use the QTreeWidget::setItemWidget method to associate the QWidget with the QTreeWidgetItem.

When you see the mousePressEvent that starts the drag, get the QTreeWidgetItem *drag_item that's under the mouse by calling QTreeWidget::itemAt(event->pos()).

When creating the QDrag, create the pixmap by doing something like this:

QWidget *w = itemWidget(drag_item,0);
QPixmap pixmap(w->size());
w->render(&pixmap);
QDrag *drag = new QDrag;
drag->setPixmap(pixmap);