C++Qt代码实现将QDockWidget中的QtoolButton复制拖拽到QtDrawingpaperEditor中
时间: 2024-02-17 14:02:12 浏览: 107
Qt 实现拖拽效果
可以通过以下步骤实现将QDockWidget中的QtoolButton复制拖拽到QtDrawingpaperEditor中:
1. 在QDockWidget中创建QtoolButton,并将其设置为可拖拽:
```cpp
QToolButton *toolButton = new QToolButton(this);
toolButton->setText("My Button");
toolButton->setAutoRaise(true);
toolButton->setCursor(Qt::OpenHandCursor);
toolButton->setDragEnabled(true);
```
2. 在QtDrawingpaperEditor中实现拖拽事件的处理函数:
```cpp
void QtDrawingpaperEditor::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
event->acceptProposedAction();
}
}
void QtDrawingpaperEditor::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
QByteArray data = event->mimeData()->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&data, QIODevice::ReadOnly);
while (!stream.atEnd()) {
int row, col;
QMap<int, QVariant> roleDataMap;
stream >> row >> col >> roleDataMap;
QString text = roleDataMap[Qt::DisplayRole].toString();
// 在QtDrawingpaperEditor中创建新的QtoolButton,并设置其文本内容
QToolButton *newButton = new QToolButton(this);
newButton->setText(text);
newButton->show();
}
event->acceptProposedAction();
}
}
```
3. 将QtoolButton拖拽到QtDrawingpaperEditor中:
在QDockWidget中按住QtoolButton左键不放,拖动鼠标到QtDrawingpaperEditor中,释放左键即可。此时QtDrawingpaperEditor中会创建一个新的QtoolButton并显示其文本内容。
阅读全文