常见操作

数据类型

C++—>QT

  1. int—-int
  2. char—-Qchar
  3. double—-double
  4. float—-float
  5. bool—-bool
  6. void—-void
  7. enum—-enum
  8. string—-QString
QString str;声明
str.append(str2);末尾追加
int length = str.size();查看长度
QChar ch = str[0];
```

9. QTimer处理时间

```c++

  1. QColor处理颜色
  2. QPixmap处理图像
  3. QImage处理图像
  4. QObject,基类
  5. QByteArray—-char*,可用于创建动态数组。
声明
QByteArray byteArray;
byteArray.append("Hello", 5);末尾追加
append(const QByteArray &other);末尾
char byte = byteArray[i];遍历,值赋给byte;
包含头尾追加,定点删除替换,清空。
  1. QVariant,联合其他不同种类数据
  2. QPoint,表示X,Y轴坐标
QPoint point;
QPoint point(x,y);
point.setX(x);
point.setY(y);设置
point.x();
point.y();访问
  1. QLine,两点一线
QLine line;
16一致,对$X_1,y_1,X_2,y_2$四个参数操作
  1. QSize,表示宽高
  2. QRect,表示矩形
Qrect rect;
17,但按顺序包含$X_1(左上角),y_19(右上角),宽,高$的顺序

……

输入输出

需要include
qDebug()<<”hello”;
将把“ ”内的内容写入日志

信号槽

配件和配件间交流的方法。
相比于return ,信号槽可以进行一些额外操作。
能返回多个信号,对应多个值,实现多个操作。
connect(button, SIGNAL(clicked()), &a, SLOT(quit()));
从左到右依次为,信号发出对象,信号行为,接收对象,接收动作。
class MyBook : public QObject,必要继承
{
Q_OBJECT,必要宏
public
MyBook(QObject *parent = 0) : QObject(parent)随手赋值
{}
void send()
{
emit sendSignal(as);
}发送信号
signals:
void sendSignal(&as);信号为as
private
char as;创建as
}
class MyMark : public QObject,必要继承
{
Q_OBJECT,必要宏
public
MyMark()
void receive(const Qstring &as)
{
qDebug() << as;
}拿到信号后的行为(槽)
}
#include<QCoreApplication>
#include "MyBook"
#include "MyMark"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
MyBook *book = new MyBook;
MyMark *mark = new MyMark;
connect(book, SIGNAL(sendSignal(QString)), mark, SLOT(receive(QString)));连接搭建
book->send();发出信号,与动作绑定的信号槽连接
return app.exec();
}

交互插件

  1. QPushButton
    #include<QPushButton>

    初始化
    QPushButton *button = new QPushButton("test",this);this为当前的窗口,“”内为按钮信息

    按键位置
    button->setGeometry(x,y,w,h);设置按钮位置,以$x,y,w,h$的方式

    按键策略
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);Expanding为扩展,Fixed为固定
    button->setSizePolicy(sizePolicy);
    button->setMinimumSize(QSize(60, 20));
    button->setMaximumSize(QSize(240, 80));
    会根据窗口的大小为按键自动变换大小,但不超过min和max

    数组
    vector<QPushButton*> button;
    对应的初始化:
    button.push_back(new QPushButton("test",this));
  2. QLabel
  3. QLineEdit
  4. QTextEdit
  5. QFileDialog
  6. QMessageBox
  7. QColorDialog

窗口

  1. QMainWindow
  2. QDialog
  3. QWidget
  4. QFrame
  5. QGroupBox
  6. QToolBox
  7. QToolBar
  8. QStatusBar
  9. QMenuBar
  10. QMenu
  11. QDockWidget
  12. QTabWidget
  13. QStackedWidget
用于页面的无缝切换。
使用方法:
1.加入QStackedWidget的页面需要new出来
2.该页面要用stack->addWidget(Widget)加入
3.第一种设置当前页面:stack->setCurrentWidget(this);
根据页面名搜索
第二种设置当前页面:stack->setCurrentIndex(index);
根据索引搜索(索引不会因为其他页面被释放而改变)
4.展示页面stack->show();

布局

Qt布局操作旨在帮助您在用户界面中组织和定位控件,确保它们在不同屏幕尺寸和分辨率下都能正确显示和响应窗口大小变化。

  1. QHBoxLayout,QVBoxLayout
    ···c++
    水平布局,垂直布局

    声明
    QHBoxLayout *layout = new QHBoxLayout;
    后者同理

    间隔
    vlayout->setSpacing(100); // 设置组件之间的间距为100像素

    边距
    hlayout->setContentsMargins(0, 0, 120, 120); // 设置布局四周的边距

    添加元件
    hlayout->addWidget(button);

    放置伸缩空间(类似于空格
    hlayout->addStretch();

    镶嵌布局
    类似于添加元件,但会自动填充剩余空间
    hlayout->addWidget(buttonwidget);
    此处添加的buttonwidget为QWidget类型的包含按钮的小部件,需要先声明
  2. QGridLayout
    类似于c++中的数组,但需要指定行列数

    ```c++
    QGridLayout *gridLayout = new QGridLayout(this);
    声明

    gridLayout->setSpacing(10);
    间隔

    for (int i = 0; i < 6; ++i) {
    for (int j = 0; j < 6; ++j)
    {
    gridLayout->addWidget(Label, i, j);
    }
    }
    添加
    得到的效果较好,各个label可以紧凑起来,若在行或列方向有空隙,则可能需要为水平或垂直布局加入addstretch()

文件

读取

#include<QFile>
#include<QTextStream>
QFile file("test.txt");打开文件
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))判断是否打开。是,则继续
readonly表示只读,Text表示转换规范
QTextStream in(&file);创建文本流对象
while (!in.atEnd())直到读完
{
QString line = in.readLine();
}
file.close();关闭文件

拖拽

需要重写Label类
$droplabel.h$

#ifndef DROPLABEL_H
#define DROPLABEL_H

#include <QLabel>
#include <QWidget>
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QApplication>
#include <QGraphicsDropShadowEffect>
#include <QGridLayout>

class DropLabel : public QLabel {
Q_OBJECT
public:
explicit DropLabel(QWidget *parent = nullptr);
void putpost(int,QGridLayout*);
//设置坐标,并传入网格的指针
void set_txt();
//修改label的文本
void findlabel(int);
//衍生到其他label
protected:
void dragEnterEvent(QDragEnterEvent *event) override;
//判断是否要接收这个拖拽
void dropEvent(QDropEvent *event) override;
//接收之后的操作
private:
int post;//位置信息
QGridLayout* grid;//指针
};

#endif // DROPLABEL_H

$droplabel.cpp$
#include "DropLabel.h"
DropLabel::DropLabel(QWidget *parent)
: QLabel(parent)
{
setAcceptDrops(true); // 接受拖放事件
}

void DropLabel::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasText()) {
event->acceptProposedAction(); // 接受拖放动作
} else {
event->ignore();
}
}

void DropLabel::dropEvent(QDropEvent *event)
{
QString droppedText = event->mimeData()->text();
if (droppedText=="1")//对拖拽的是哪个图片进行标记
{
setText("byd"); // 改变文本表示图片已放置在此
int num1=post+1;
if(num1>0&&num1<36)//判断
{
findlabel(num1);
}
event->accept();
}
}

void DropLabel::putpost(int i,QGridLayout* g)
{
post=i;
grid=g;
}

void DropLabel::set_txt()
{
setText("byd");
}
void DropLabel::findlabel(int i)
{
int x=i/6;
int y=i%6;
QWidget *widget = grid->itemAtPosition(x, y)->widget();
DropLabel *dropLabel = qobject_cast<DropLabel*>(widget); // 尝试转换为DropLabel
dropLabel->set_txt();
}


$draglabel.h$
#ifndef DRAGLABEL_H
#define DRAGLABEL_H

#include <QWidget>
#include <QLabel>
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QApplication>
#include <QGraphicsDropShadowEffect>
#include <QString>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QPainter>

class DragLabel : public QLabel {
Q_OBJECT
public:
explicit DragLabel(QWidget *parent = nullptr);
void put_text(QString);
protected:
void mousePressEvent(QMouseEvent *event) override;
//左键鼠标
void mouseMoveEvent(QMouseEvent *event) override;
//图标移动
private:
QString text;//判断文本(mimetext)
QPoint dragStartPos;
};

#endif // DRAGLABEL_H

$draglabel.cpp$
#include "DragLabel.h"

DragLabel::DragLabel(QWidget *parent)
: QLabel(parent)
{
setMouseTracking(true); // 跟踪鼠标移动
setCursor(Qt::OpenHandCursor); // 设置手型光标
}

void DragLabel::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
dragStartPos = event->pos(); // 记录鼠标按下时的位置
}
QLabel::mousePressEvent(event);
}
void DragLabel::put_text(QString t)
{
text=t;
}
void DragLabel::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) { // 检查鼠标左键是否被按下
QPoint diff = event->pos() - dragStartPos; // 计算鼠标移动的距离
if (diff.manhattanLength() < QApplication::startDragDistance()) {
return; // 如果移动距离小于启动拖动的距离,则不执行拖动
}
//第一部分结束

// 创建拖动图像并应用虚化效果
QPixmap originalPixmap = pixmap(Qt::ReturnByValue);
QGraphicsScene scene;
QGraphicsPixmapItem *pixmapItem = scene.addPixmap(originalPixmap);
QGraphicsBlurEffect *blurEffect = new QGraphicsBlurEffect;
blurEffect->setBlurRadius(5); // 调整此值以改变虚化程度
pixmapItem->setGraphicsEffect(blurEffect);
//将模糊效果(blurEffect)应用于 pixmapItem,从而将其模糊化。
QImage blurredImage(scene.width(), scene.height(), QImage::Format_ARGB32);
QPainter painter(&blurredImage);
scene.render(&painter);
//将模糊场景捕获为图像
QPixmap blurredPixmap = QPixmap::fromImage(blurredImage);

// 实现拖动逻辑
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
mimeData->setText(text); // 将标签的文本作为MIME数据
drag->setMimeData(mimeData);
drag->setPixmap(blurredPixmap); // 使用虚化后的图像
drag->setHotSpot(QPoint(0, 0)); // 热区设置在图像的左上角,让图像跟随鼠标箭头
drag->exec();
}
QLabel::mouseMoveEvent(event);
}

$main.cpp$
QHBoxLayout * a=new QHBoxLayout(this);
QGridLayout *gridLayout = new QGridLayout(this);
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
DropLabel *dropLabel = new DropLabel(this);
dropLabel->putpost(i*6+j,gridLayout);
dropLabel->setText(QString::number(i * 6 + j + 1)); // 初始文本
gridLayout->addWidget(dropLabel, i, j);
}
}

// 创建DragLabel并设置图片
DragLabel *dragLabel = new DragLabel(this);
dragLabel->put_text("1");
QPixmap pixmap(":/D:/图片/实训/4.png"); // 图片路径
dragLabel->setPixmap(pixmap);
a->addLayout(gridLayout);
a->addWidget(dragLabel);// 示例位置,可调整

接下来,就可以使用拖拽了。
其中,拖拽时的虚影固定在鼠标右下角,方便操作

比比几句

QT中当父类Widget销毁时,子类Widget也会销毁.即传入了父类指针的对象,子类会自动销毁。不放心的话可以用delete来手动销毁。