最近项目的需要,需要做一个日历。于是找资料,原来Qt中已经封装好了一个类QCalendarWidget,专门做日历的。于是我用QlineEdit加QFontComboBox。做了一个简易的日历
一下是代码
// "line_edit.h"
#include <QLineEdit>
#include <QMouseEvent>
class line_edit : public QLineEdit
{
Q_OBJECT
public:
explicit line_edit(QWidget *parent = 0);
virtual void mousePressEvent(QMouseEvent *event);
//void mouseReleaseEvent(QMouseEvent *event);
signals:
//自定义clicked()信号,在mousePressEvent事件发生时触发
void clicked();
};
//line_edit.cpp
#include "line_edit.h"
line_edit::line_edit(QWidget *parent):
QLineEdit(parent)
{
setFixedSize(100,20);
}
void line_edit::mousePressEvent(QMouseEvent *event)
{
//如果单击了就触发clicked信号
if (event->button() == Qt::LeftButton)
{
//触发clicked信号
emit clicked();
}
//将该事件传给父类处理
QLineEdit::mousePressEvent(event);
}
//"mainwindow.h"
#include <QMainWindow>
#include <QCalendarWidget>
#include "line_edit.h"
#include <QFontComboBox>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QCalendarWidget *caledar;
line_edit *lineedit;
QFontComboBox *hms;
QString str;
public slots:
void ok();
};
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDate>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setFixedSize(500,400);
caledar = new QCalendarWidget(this);
lineedit = new line_edit(this);
hms = new QFontComboBox(this);
lineedit->setGeometry(100,70,150,30);
caledar->setGeometry(100,100,200,200);
hms->clear();
hms->insertItem(0,"00:00");
hms->insertItem(1,"00:30");
hms->insertItem(2,"01:00");
hms->insertItem(3,"01:30");
hms->setGeometry(200,70,70,20);
caledar->hide();
connect(lineedit,SIGNAL(clicked()),caledar,SLOT(show()));
connect(lineedit,SIGNAL(textChanged(QString)),caledar,SLOT(show()));
connect(caledar,SIGNAL(clicked(QDate)),this,SLOT(ok()));
}
MainWindow::~MainWindow()
{
}
void MainWindow::ok()
{
QDate date = caledar->selectedDate();
qDebug()<<date.year()<<date.month()<<date.day();
int y = date.year();
int m = date.month();
int d = date.day();
QString str_total;
str_total = QString::number(y)+"-"+QString::number(m)+"-"+QString::number(d)+" ";
lineedit->setText(str_total);
caledar->hide();
}
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
以下是运行效果图