本篇内容介绍了“基于Qt怎么实现可拖动自定义控件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
使用QT实现自定义类卡牌控件Card,使其能在父类窗口上使用鼠标进行拖动。
控件类头文件card.h
#ifndef CARD_H#define CARD_H#include <QWidget>#include <QPaintEvent>#include <QPainter>#include <QMouseEvent>class Card:public QWidget{ Q_OBJECTpublic: explicit Card(QWidget *parent = nullptr); ~Card();protected: 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(this); //信号发送该控件地址}
以上是基于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_OBJECTpublic: 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), ui(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;}//获取控件坐标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();}
“基于Qt怎么实现可拖动自定义控件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!