QT像浏览器一样Tab按钮长按可以拖动出一个窗口,然后可以拖回去的示例代码
时间: 2024-03-26 09:38:17 浏览: 105
这里是一个简单的示例代码,可以实现QT的Tab按钮长按可以拖动出一个窗口,然后可以拖回去的功能:
```cpp
#include <QTabBar>
#include <QMouseEvent>
#include <QMimeData>
#include <QDrag>
#include <QPainter>
class MyTabBar : public QTabBar
{
public:
MyTabBar(QWidget* parent = nullptr) : QTabBar(parent) {}
~MyTabBar() {}
protected:
void mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
m_startPos = event->pos();
}
QTabBar::mousePressEvent(event);
}
void mouseMoveEvent(QMouseEvent* event)
{
if (!(event->buttons() & Qt::LeftButton))
{
return;
}
if ((event->pos() - m_startPos).manhattanLength() < QApplication::startDragDistance())
{
return;
}
int index = tabAt(m_startPos);
if (index < 0)
{
return;
}
QWidget* widget = tabButton(index, QTabBar::RightSide);
if (!widget)
{
return;
}
QPixmap pixmap(widget->size());
widget->render(&pixmap);
QMimeData* mimeData = new QMimeData;
mimeData->setData("application/x-tabbtn", QByteArray::number(index));
QDrag* drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(pixmap);
drag->setHotSpot(event->pos() - widget->pos());
setTabEnabled(index, false);
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction)
{
setTabEnabled(index, true);
}
else
{
setTabEnabled(index, true);
}
}
void dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasFormat("application/x-tabbtn"))
{
event->acceptProposedAction();
}
}
void dragMoveEvent(QDragMoveEvent* event)
{
if (event->mimeData()->hasFormat("application/x-tabbtn"))
{
event->acceptProposedAction();
}
}
void dragLeaveEvent(QDragLeaveEvent* event)
{
Q_UNUSED(event);
}
void dropEvent(QDropEvent* event)
{
if (event->mimeData()->hasFormat("application/x-tabbtn"))
{
QByteArray data = event->mimeData()->data("application/x-tabbtn");
int index = data.toInt();
if (index >= 0 && index < count())
{
QWidget* widget = tabButton(index, QTabBar::RightSide);
if (widget)
{
QPoint pos = event->pos() - widget->rect().center();
widget->move(pos);
widget->show();
}
}
event->acceptProposedAction();
}
}
void paintEvent(QPaintEvent* event)
{
QTabBar::paintEvent(event);
if (m_isDragging)
{
QPainter painter(this);
QPixmap pixmap = tabButton(m_dragIndex, QTabBar::RightSide)->grab();
painter.drawPixmap(m_dragPos, pixmap);
}
}
private:
QPoint m_startPos;
bool m_isDragging = false;
QPoint m_dragPos;
int m_dragIndex;
void startDrag(int index, const QPoint& pos)
{
QWidget* widget = tabButton(index, QTabBar::RightSide);
if (!widget)
{
return;
}
m_isDragging = true;
m_dragIndex = index;
m_dragPos = pos - widget->rect().center();
}
};
```
使用方法:
在创建`QTabWidget`的时候,将其`QTabBar`替换为`MyTabBar`即可:
```cpp
QTabWidget* tabWidget = new QTabWidget(this);
tabWidget->setTabBar(new MyTabBar(tabWidget));
```
希望这个示例代码能够对你有所帮助!
阅读全文