PS: 本文使用的是Qt 4.8.4版本,不同版本代码可能会有差异
设置窗口标题
setWindowTitle(QString::fromLocal8Bit("易语言"));
禁用窗口最大化按钮
setWindowFlags(Qt::Dialog | Qt::WindowMinimizeButtonHint);
禁止窗口改变大小
setFixedSize(this->width(), this->height());
鼠标左键按下
// 重写虚函数
void mousePressEvent(QMouseEvent* event); void QLoginSuccess::mousePressEvent(QMouseEvent* event) { m_start = event->pos(); // 获取当前lable空间的坐标 QPoint lablePos = ui.label->pos(); if ((m_start.x() > lablePos.x()) && (m_start.x() < (lablePos.x() +64)) && (m_start.y() > lablePos.y()) && (m_start.y() < (lablePos.y() +64))) { qDebug() << GBK::ToUnicode("在控件上!") << endl; isNeedDrag = true; } }
鼠标移动
void mouseMoveEvent(QMouseEvent* event); void QLoginSuccess::mouseMoveEvent(QMouseEvent* event) { if (isNeedDrag == true) { m_end = event->pos(); m_PosVector.push_back(m_end); if (m_PosVector.size() >= 2) { QPoint pp = m_PosVector.at(m_PosVector.size() - 1) - m_PosVector.at(m_PosVector.size() - 2) + ui.label->pos(); ui.label->move(pp.x(), pp.y()); } } }
鼠标释放
void mouseReleaseEvent(QMouseEvent* event); void QLoginSuccess::mouseReleaseEvent(QMouseEvent* event) { // 标志位置为false isNeedDrag = false; }
获取键盘按键
void keyPressEvent(QKeyEvent * event); void PlaneGame::keyPressEvent(QKeyEvent * event) { if (event->key() == Qt::Key_Left) { if (ui.meLabel->pos().x() >= 3) { ui.meLabel->move(ui.meLabel->pos().x() - 10, ui.meLabel->pos().y()); } } else if (event->key() == Qt::Key_Right) { if (ui.meLabel->pos().x() <= 429) { ui.meLabel->move(ui.meLabel->pos().x() + 10, ui.meLabel->pos().y()); } } else if (event->key() == Qt::Key_F1) { CBullet* bullet = new CBullet(this); bullet->move(ui.meLabel->pos().x() + 22, ui.meLabel->pos().y() + 11); bullets.push_back(bullet); bullet->show(); } }
关闭对话框事件处理函数
void closeEvent(QCloseEvent* event);
Qt 生成随机数
// 生成随机数种子(一般在构造函数执行一次就行) qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); // 随机产生一个0到7之间的数 int n = qrand() % 8;