QT 5.14 写一个新增,修改记录的功能,请写一个实例。
时间: 2024-05-05 13:17:54 浏览: 101
实例QT程序 —— QTableWidget 表格新增/删除行功能
5星 · 资源好评率100%
好的,以下是一个简单的实例代码:
```c++
#include <QMainWindow>
#include <QTextEdit>
#include <QToolBar>
#include <QAction>
#include <QMessageBox>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
m_textEdit = new QTextEdit(this);
setCentralWidget(m_textEdit);
m_toolBar = addToolBar(tr("Record"));
m_addAction = new QAction(tr("Add"), this);
m_modifyAction = new QAction(tr("Modify"), this);
m_toolBar->addAction(m_addAction);
m_toolBar->addAction(m_modifyAction);
connect(m_addAction, &QAction::triggered, this, &MainWindow::addRecord);
connect(m_modifyAction, &QAction::triggered, this, &MainWindow::modifyRecord);
}
private slots:
void addRecord()
{
QString newRecord = QInputDialog::getText(this, tr("Add Record"), tr("Enter new record:"));
if (!newRecord.isEmpty())
{
m_textEdit->append(newRecord);
QMessageBox::information(this, tr("Record"), tr("New record added!"));
}
}
void modifyRecord()
{
int currentLine = m_textEdit->textCursor().blockNumber();
QString currentRecord = m_textEdit->document()->findBlockByLineNumber(currentLine).text().trimmed();
if (currentRecord.isEmpty())
{
QMessageBox::warning(this, tr("Record"), tr("No record selected!"));
}
else
{
QString newRecord = QInputDialog::getText(this, tr("Modify Record"), tr("Modify record:"), QLineEdit::Normal, currentRecord);
if (!newRecord.isEmpty())
{
QTextCursor cursor = m_textEdit->textCursor();
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
cursor.insertText(newRecord);
QMessageBox::information(this, tr("Record"), tr("Record modified!"));
}
}
}
private:
QTextEdit *m_textEdit;
QToolBar *m_toolBar;
QAction *m_addAction;
QAction *m_modifyAction;
};
```
希望这个实例代码可以帮助你实现新增、修改记录的功能。现在,你可以继续问我其他问题了。
阅读全文