qt 5.x 初探(1)
嘛。。为了系统安全课来学一波qt...
现在算是写出了一个可以打开文件,保存文件的记事本。。。
接下来要搞定的事情是。。。如何写一个自定义的事件。。。比如计算个开方之类的。。。
放一波代码好了。。。
1#include <QAction>
2#include <QMenuBar>
3#include <QMessageBox>
4#include <QStatusBar>
5#include <QToolBar>
6#include <QDebug>
7#include <QTextEdit>
8#include <QFileDialog>
#include "mainwindow.h"
1MainWindow::MainWindow(QWidget *parent) :
2 QMainWindow(parent)
3{
1 openAction = new QAction(QIcon(":/images/file-open"), tr("&Open..."), this);
2 openAction->setShortcuts(QKeySequence::Open);
3 openAction->setStatusTip(tr("Open an existing file"));
1 saveAction = new QAction(QIcon(":/images/file-open"), tr("&Save..."), this);
2 saveAction->setShortcuts(QKeySequence::Save);
3 saveAction->setStatusTip(tr("Save a new file"));
1 QMenu *file = menuBar()->addMenu(tr("&File"));
2 file->addAction(openAction);
3 file->addAction(saveAction);
1 QToolBar *toolBar = addToolBar(tr("&File"));
2 toolBar->addAction(openAction);
3 toolBar->addAction(saveAction);
textEdit = new QTextEdit(this);
setCentralWidget(textEdit);
connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
connect(saveAction, &QAction::triggered, this, &MainWindow::saveFile);
}
1MainWindow::~MainWindow()
2{
3}
1void MainWindow::openFile()
2{
3 QString path = QFileDialog::getOpenFileName(this,
4 tr("Open File"),
5 ".",
6 tr("Text Files(*.txt)"));
7 if(!path.isEmpty()) {
8 QFile file(path);
9 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
10 QMessageBox::warning(this, tr("Read File"),
11 tr("Cannot open file:\n%1").arg(path));
12 return;
13 }
14 QTextStream in(&file);
15 textEdit->setText(in.readAll());
16 file.close();
17 } else {
18 QMessageBox::warning(this, tr("Path"),
19 tr("You did not select any file."));
20 }
21}
1void MainWindow::saveFile()
2{
3 QString path = QFileDialog::getSaveFileName(this,
4 tr("Open File"),
5 ".",
6 tr("Text Files(*.txt)"));
7 if(!path.isEmpty()) {
8 QFile file(path);
9 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
10 QMessageBox::warning(this, tr("Write File"),
11 tr("Cannot open file:\n%1").arg(path));
12 return;
13 }
14 QTextStream out(&file);
15 out << textEdit->toPlainText();
16 file.close();
17 } else {
18 QMessageBox::warning(this, tr("Path"),
19 tr("You did not select any file."));
20 }
21}
1#include "mainwindow.h"
2#include <QApplication>
3#include <QSpinBox>
4#include <QSlider>
5#include <QHBoxLayout>
// !!! Qt 5
1int main(int argc, char *argv[])
2{
3 QApplication app(argc, argv);
MainWindow win;
win.show();
return app.exec();
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextEdit>
1namespace Ui {
2class MainWindow;
3}
1class MainWindow : public QMainWindow
2{
3 Q_OBJECT
1public:
2 MainWindow(QWidget *parent = 0);
3 ~MainWindow();
1private:
2 Ui::MainWindow *ui;
3 void openFile();
4 void saveFile();
5 QAction *openAction;
6 QAction *saveAction;
7 QTextEdit *textEdit;
8};
#endif // MAINWINDOW_H
大概看了一下午。。。这东西看起来虽然说完全没难度。。。但是还是很麻烦啊。。。