我是Qt Creator和编码的新手,我正在尝试创建一个应用程序,其中我有一个颜色选项列表和一个区域,我可以拖动这些选项并创建一个图形项目我选择的颜色,这里是代码:
我创建了QListWidget
并暂时添加了两个QListWidgetItem
itens:
OptionList::OptionList(QWidget *parent) : QListWidget(parent)
{
this->setDragEnabled(true);
this->setDropIndicatorShown(true);
this->setSelectionMode(QAbstractItemView::SingleSelection);
this->setDefaultDropAction(Qt::CopyAction);
this->setViewMode(QListView::ListMode);
QListWidgetItem *blue = new QListWidgetItem;
blue->setText("Blue");
blue->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable |
Qt::ItemIsDragEnabled);
addItem(blue);
QListWidgetItem *red = new QListWidgetItem;
red->setText("Red");
red->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable |
Qt::ItemIsDragEnabled);
addItem(red);
}
我创建了一个QgraphicsPathItem
,它接收一个字符串,具体取决于字符串,它会改变颜色
Block::Block(QString color, QGraphicsItem *parent) : QGraphicsPathItem(parent)
{
QPainterPath p;
p.addRoundedRect(0, 0, 150, 50, 2, 2);
setPath(p);
setPen(QPen(Qt::black));
if (color == "Blue")
{
setBrush(Qt::blue);
}
else if (color == "Red")
{
setBrush(Qt::red);
}
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
}
然后,我创建了从MyScene
派生的QGraphicsScene
类,并重新实现了dragEnterEvent
,dragMoveEvent
和dropEvent
#include "myscene.h"
MyScene::MyScene()
{
setBackgroundBrush(Qt::lightGray);
}
void MyScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
event->setAccepted(true);
}
void MyScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
event->setAccepted(true);
}
void MyScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
QString color;
color = event->mimeData()->text();
Block *newBlock = new Block(color);
QPointF posView = event->scenePos();
newBlock->setPos(posView);
addItem(newBlock);
}
我尝试使用QString color; color = event->mimeData()->text();
,但它没有工作
我知道它与QMimeData
课程有关,但我不知道该怎么做
如何从列表中的项目中获取文本并将其传递给Block类以更改其颜色?
答案 0 :(得分:0)
您必须对数据进行解码,因为QListWidget
QAbstractItemView
支持多选。
void MyScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event){
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->setAccepted(true);
}
void MyScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event){
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->setAccepted(true);
}
void MyScene::dropEvent(QGraphicsSceneDragDropEvent *event){
QByteArray encoded = event->mimeData()->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&encoded, QIODevice::ReadOnly);
QStringList colors;
while (!stream.atEnd())
{
int row, col;
QMap<int, QVariant> roleDataMap;
stream >> row >> col >> roleDataMap;
colors << roleDataMap[Qt::DisplayRole].toString();
}
QPointF posView = event->scenePos();
for(const QString & color: colors){
Block *newBlock = new Block(color);
newBlock->setPos(posView);
addItem(newBlock);
}
}