關(guān)鍵詞:QAction
的信號(hào)、文件打開操作、文件保存操作、文件另存為操作
1. QAction
的信號(hào)
-
QAction
被點(diǎn)擊之后會(huì)產(chǎn)生一個(gè)triggered信號(hào)
通過信號(hào)與槽的機(jī)制能夠捕捉對(duì)QAction
對(duì)象的操作,項(xiàng)目中可以將多個(gè)信號(hào)映射到同一個(gè)槽函數(shù)
connect(action,
SIGNAL(triggered()),
this,
SLOT(slot_function()))
2. 文件打開操作
void MainWindow::onFileOpen()
{
QString path = showFileDialog(QFileDialog::AcceptOpen, "Open");
if( path != "")
{
QFile file(path);
if( file.open(QIODevice::ReadOnly | QIODevice::Text)) //文件打開成功
{
mainEditor.setPlainText(QString(file.readAll()));
file.close();
m_filePath = path;
setWindowTitle("NotePad - [" + m_filePath + "]");
}
else // 文件打開失敗娘锁,彈出對(duì)話框提示
{
showErrorMessage(QString("Open file error! \n\n") + "\"" + path + "\"");
}
}
}
3. 文件保存操作
void MainWindow::onFileSave()
{
if(m_filePath == "")
{
m_filePath = showFileDialog(QFileDialog::AcceptSave, "Save");
}
if( m_filePath != "")
{
QFile file(m_filePath);
if( file.open(QIODevice::WriteOnly | QIODevice::Text) )
{
QTextStream out(&file);
out << mainEditor.toPlainText();
file.close();
setWindowTitle("NotePad - [" + m_filePath + "]");
}
else
{
showErrorMessage(QString("Save file error! \n\n") + "\"" + m_filePath + "\"");
m_filePath = "";
}
}
}
4. 文件另存為操作
void MainWindow::onFileSaveAs()
{
QString path = showFileDialog(QFileDialog::AcceptSave, "Save As");
if (path != "")
{
QFile file(path);
if( file.open(QIODevice::WriteOnly | QIODevice::Text) )
{
QTextStream out(&file);
out << mainEditor.toPlainText();
file.close();
m_filePath = path;
setWindowTitle("NotePad - [" + m_filePath + "]");
}
else
{
showErrorMessage(QString("Save file error! \n\n") + "\"" + path + "\"");
}
}
}
5. 小結(jié)
- Qt項(xiàng)目中盡量將界面代碼與功能代碼分離開
- Qt項(xiàng)目開發(fā)時(shí)盡量復(fù)用平臺(tái)中提供的相關(guān)組件
- Qt項(xiàng)目中的多數(shù)情況都是編寫相應(yīng)的槽函數(shù)
槽函數(shù)用于相應(yīng)用戶操作
槽函數(shù)是具體功能的觸發(fā)點(diǎn)
聲明:此文章僅是本人在學(xué)習(xí)狄泰QT實(shí)驗(yàn)分析課程所做的筆記,文章中包含狄泰軟件資料內(nèi)容饺鹃,一切版權(quán)歸狄泰軟件所有莫秆!
實(shí)驗(yàn)環(huán)境:ubuntu10 + Qt Creator2.4.1 + Qt SDK 4.7.4