基于Qt实现可拖动自定义控件
使用QT实现自定义类卡牌控件Card,使其能在父类窗口上使用鼠标进行拖动。
控件类头文件card.h
#ifndef CARD_H #define CARD_H #include <QWidget> #include <QPaintEvent> #include <QPainter> #include <QMouseEvent> class Card:public QWidget { Q_OBJECT public: explicit Card(QWidget *parent = nullptrwww.devze.com); ~Card(); protected:www.devze.com void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; signals: void sendSelf(Card *w); }; #endif // CARD_H
控件类头文件card.cpp
#include "card.h" Card::Card(QWidget *parent):QWidget(parent) { this->setGeometry(0,0,200,400); //设置控件窗口大小 } Card::~Card() { } void Card::paintEvent(QPaintEvent *event) { QPainter painter(this); //创建画笔 painter.setRenderHint(QPainter::Antialiasing,true); QBrush brush; //创建笔刷 brush.setColor(Qt::yellow); //设置笔刷颜色 brush.setStyle(Qt::SolidPattern); painter.setBrush(brush); //设置画笔笔刷 painter.drawRoundedRect(QRectF(5,5,190,390),10,10); //绘制圆角矩形并填充 } void Card::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event); emit sendSelf(t编程客栈his); //信号发送该控件地址 }
以上是基于widget类的控件类;
父窗口头文件mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "card.h" #include <QDebug> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; Card* cd[8]; Card *temp; QPoint startP; QPoint yuanP; private slots: void getObject(Card *w); protected: void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; }; #endif // MAINWINDOW_H
父窗口头文件mainwindow.cpp编程客栈
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), u开发者_Python开发i(new Ui::MainWindow) { ui->setupUi(this); for(int i=0;i<8;i++) { cd[i] = new Card(this); connect(cd[i],&Card::sendSelf,this,&MainWindow::getObject); cd[i]->move(i%4*200,i/4*400+20); } } MainWindow::~MainWindow() { delete ui; } /android/获取控件坐标 void MainWindow::getObject(Card *w) { temp = w; startP = cursor().pos()-this->pos(); yuanP = temp->pos(); /*将此小部件提升到父小部件堆栈的顶部*/ temp->raise(); } //移动事件 void MainWindow::mouseMoveEvent(QMouseEvent *event) { temp->move(yuanP.x()+event->x()-startP.x(),yuanP.y()+event->y()-startP.y()); } //拖拽对象置顶,卡牌积压的时候,拖动的那张卡牌置顶 void MainWindow::mouseReleaseEvent(QMouseEvent *event) { temp->raise(); }
以下是工程源码:
链接:https://pan.baidu.com/s/1o1OXI-GYCf6FcHd1Bt5ycg
提取码:ve9v
到此这篇关于基于Qt实现可拖动自定义控件的文章就介绍到这了,更多相关Qt可拖动自定义控件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论