如何将他改编成可视化界面
时间: 2023-09-07 10:12:09 浏览: 36
将控制台程序改编成可视化界面需要使用特定的 GUI 框架,如 Qt、MFC、WinForms 等。以下是一个使用 Qt 框架的示例代码:
```c++
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QWidget>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QPushButton>
#include <vector>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
int year;
int pages;
public:
void set_title(string t) { title = t; }
void set_author(string a) { author = a; }
void set_year(int y) { year = y; }
void set_pages(int p) { pages = p; }
string get_title() { return title; }
string get_author() { return author; }
int get_year() { return year; }
int get_pages() { return pages; }
};
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr) : QMainWindow(parent) {
setWindowTitle("图书管理系统");
QWidget* centralWidget = new QWidget(this);
QGridLayout* layout = new QGridLayout(centralWidget);
QLabel* label1 = new QLabel("书名:", this);
QLineEdit* lineEdit1 = new QLineEdit(this);
QLabel* label2 = new QLabel("作者:", this);
QLineEdit* lineEdit2 = new QLineEdit(this);
QLabel* label3 = new QLabel("出版年份:", this);
QSpinBox* spinBox1 = new QSpinBox(this);
QLabel* label4 = new QLabel("页数:", this);
QSpinBox* spinBox2 = new QSpinBox(this);
QPushButton* button1 = new QPushButton("添加", this);
QPushButton* button2 = new QPushButton("显示列表", this);
layout->addWidget(label1, 0, 0);
layout->addWidget(lineEdit1, 0, 1);
layout->addWidget(label2, 1, 0);
layout->addWidget(lineEdit2, 1, 1);
layout->addWidget(label3, 2, 0);
layout->addWidget(spinBox1, 2, 1);
layout->addWidget(label4, 3, 0);
layout->addWidget(spinBox2, 3, 1);
layout->addWidget(button1, 4, 0);
layout->addWidget(button2, 4, 1);
connect(button1, &QPushButton::clicked, this, [=]() {
Book book;
book.set_title(lineEdit1->text().toStdString());
book.set_author(lineEdit2->text().toStdString());
book.set_year(spinBox1->value());
book.set_pages(spinBox2->value());
books.push_back(book);
lineEdit1->clear();
lineEdit2->clear();
spinBox1->clear();
spinBox2->clear();
});
connect(button2, &QPushButton::clicked, this, [=]() {
QString str;
for (int i = 0; i < books.size(); i++) {
str += "书名:" + QString::fromStdString(books[i].get_title()) + "\n";
str += "作者:" + QString::fromStdString(books[i].get_author()) + "\n";
str += "出版年份:" + QString::number(books[i].get_year()) + "\n";
str += "页数:" + QString::number(books[i].get_pages()) + "\n";
str += "---------------------\n";
}
QLabel* label = new QLabel(str, this);
label->show();
});
setCentralWidget(centralWidget);
}
private:
vector<Book> books;
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "main.moc"
```
该程序使用 Qt 框架实现了一个简单的图书管理系统,包括一个窗口、多个标签、文本框、按钮等控件,并显示了一个管理的图书列表。用户可以在窗口中输入每本书的标题、作者、出版年份和页数,并使用“添加”按钮将其添加到列表中。用户还可以使用“显示列表”按钮查看当前管理的所有图书的详细信息。