2012年2月17日 星期五

如何分析SMBIOS

最在在porting新的function,有需要更新SMBIOS的資料,
因此,學會了如何簡單的分析SMBIOS。

SMBIOS有很多的type,每一個type分別有要特別存放的data,
同時,每一個type有其不同的struct,
這一些部分一定要參考spec,
spec有定義,
而我目前就先以SMBIOS type1為例。

如果要讀取BIOS的相關資訊,可以下載RW-Everything這一個軟體,
裡面有一個讀取SMBIOS的功能,並且會幫你解析出來,是一個非常棒的軟體,而且是免費的。

另外,SMBIOS,在網路上Search就有了,我使用的版本是System Management BIOS (SMBIOS) Reference Specification v.2.7.1的版本。

下面就是Specification裡面對type 1 header的定義。

而下面就是透過RW-Everything讀取出來的SMBIOS data


SMBIOS的每一個type分為header與string兩大部分,前面全部都是Header的部分,而後面的部分都是string的部分。而每一個string跟string之間,都是以00(一個byte)當作一個分隔。
並且以00 00(二個byte)則是代表這一個type的string的結束。

2012年2月15日 星期三

在define中連接字串與數字

若定義可以設定的好,其實超好用的~

#include <stdio.h>

#define LINE_FILE(x,y) "Line " #y " of file" x
#define _LINE_FILE_(x,y) LINE_FILE(x , y)
#define __LINE_FILE__ _LINE_FILE_( __FILE__ , __LINE__ )

#define MyMacro(a,b,c) a##b##c

int main (
)
{
const char *pwsz = __LINE_FILE__;
const char *MyMacro(A,B,c) = "good";
printf("%s\n",pwsz);
printf("%s\n",MyMacro(A,B,c));
return 0;
}


參考資料:
EFI v.s #define
#define連接字串和數字 『轉錄』

2011年10月23日 星期日

Qt - 依QLineEdit的內容自動調整整個視窗的大小

在Qt - 選擇資料夾或特定的檔案的例子中,當使用者選擇檔案或資料夾後,會將其完整路徑放到QLineEdit裡面~
但是,若路徑過長,並不會調整整個視窗的大小,讓使用都可以完整的看到其路徑。

若要調整其視窗大小,必需要調整Layout的相關關係~~

在Qt裡面,若有受到Layout的控制的話,裡面的元件的大小會受到以下兩個因素影響
1. Qt Layout的限制
QLayout::SetDefaultConstraint
最小尺吋設定為minimumSize ()
QLayout::SetFixedSize
視窗為sizeHint (),且不能被改變大小。
QLayout::SetMinimumSize
視窗被設定為minimumSize ()且不能被變的更小
QLayout::SetMaximumSize
視窗被設定為maximumSize ()且不能被變的更大
QLayout::SetMinAndMaxSize
最小尺吋為minimumSize ()、最大尺吋是maximumSize ()
QLayout::SetNoConstraint
不受到Layout的控制
2. 子視窗本身也受到自己的size policies及其最大/最小值的影響
QSizePolicy::Fixed
sizeHint () - sizeHint ()
QSizePolicy::Minimum
sizeHint () - 無限大
QSizePolicy::Maximum
0 - sizeHint ()
QSizePolicy::Preferred
0 - 無限大
QSizePolicy::Expanding
0 - 無限大
QSizePolicy::MinimumExpanding
sizeHint () - 無限大
QSizePolicy::Ignored
0 - 無限大

以下就是由Qt - 選擇資料夾或特定的檔案改的結果
main.cpp

#include <QApplication>
#include "MyWidget.h"

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

MyWidget myWidget;

myWidget.show ();

return app.exec ();
}

MyWidget.h
#ifndef _MY_WIDGET_H_
#define _MY_WIDGET_H_

#include <QWidget>

class QLabel;
class QPushButton;
class QLineEdit;

class MyWidget : public QWidget {
Q_OBJECT

public:
MyWidget (QWidget *parent = 0);

private slots:
void browse ();
void ChangeSelectFile (bool);
void AdjustMainWindowSize (const QString &);

private:
QLabel *myLabel;
QPushButton *myPushButton;
QLineEdit *myLineEdit;
bool SelectFile;
};

#endif //#ifndef _MY_WIDGET_H_

MyWidget.cpp
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QGroupBox>
#include <QRadioButton>
#include <QSizePolicy>

#include "MyWidget.h"

MyWidget::MyWidget (QWidget *parent) : QWidget (parent) {
//
// init
//

myLabel = NULL;
myLineEdit = NULL;
myPushButton = NULL;

//
// Create Label component
//

myLabel = new QLabel (tr ("Target Name"), this);

//
// Create LineEdit component
//

myLineEdit = new QLineEdit (this);

//
// Set the width of QLineEdit from sizeHint () to max
//

myLineEdit->setSizePolicy (QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);

//
// Create GroupBox and RadioButton component
//

QGroupBox *box = new QGroupBox (tr ("Select Type"));
QRadioButton *radio1 = new QRadioButton (tr ("File"));
QRadioButton *radio2 = new QRadioButton (tr ("Directory"));

//
// Set the default checked RadioButton for SelectFile
//

radio1->setChecked (true);
SelectFile = true;

//
// Set RadioButton into QHBoxLayout
// And set RadioButton into same GroupBox
//

QVBoxLayout *VLayout = new QVBoxLayout;
VLayout->addWidget (radio1);
VLayout->addWidget (radio2);
box->setLayout (VLayout);

//
// Create QPushButton component
//

myPushButton = new QPushButton (tr ("&Browse..."), this);

//
// Add all the components into QHBoxLayout
//

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget (myLabel);
layout->addWidget (myLineEdit);
layout->addWidget (box);
layout->addWidget (myPushButton);

//
// Set main window to the sizeHint () and can not be changed
//

layout->setSizeConstraint (QLayout::SetFixedSize);
// layout->setSizeConstraint (QLayout::SetMinimumSize);

//
// Set the main Layout for MyWidget
//

this->setLayout (layout);

//
// Set the SIGNAL and SLOT for this component
//

connect (myPushButton, SIGNAL (clicked ()), SLOT (browse ()));
connect (radio1, SIGNAL (toggled (bool)), this, SLOT (ChangeSelectFile (bool)));

//
// When the content of QLineEdit changed, try to resize the Main Window
//

connect (myLineEdit, SIGNAL (textChanged (const QString &)), this, SLOT (AdjustMainWindowSize (const QString &)));
}

void MyWidget::browse () {

QString TargetItem;

QFileDialog myFileDialog (this);
if (SelectFile) {
TargetItem = myFileDialog.getOpenFileName (this, tr ("Open File"), QDir::currentPath (), tr ("All C++ files (*.cpp *.h)"));
} else {
TargetItem = myFileDialog.getExistingDirectory (this, tr ("Select Folder"), QDir::currentPath ());
}
if (TargetItem.isEmpty ()) {
// myLineEdit->setText (myFileDialog.directory ().absolutePath ());
// myLineEdit->clear ();
// do nothing
} else {
myLineEdit->setText (TargetItem);
}
}

void MyWidget::ChangeSelectFile (bool checked) {
SelectFile = checked;
}

void MyWidget::AdjustMainWindowSize (const QString & text) {
QFont myFont;
QFontMetrics fm (myFont);

//
// Calculate the width pixel by the number of word
//

myLineEdit->setMinimumWidth (fm.width (myLineEdit->text ()));

//
// Readjust the main window size by new MinimumWidth
//

// resize (sizeHint ());
}


這裡有一些部分要特別注意~
myLineEdit->setSizePolicy (QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);

設定QLineEdit自身的尺寸策略(size policies)
寬度是sizeHint () ~ 無窮大
高度是限制在sizeHint ()

layout->setSizeConstraint (QLayout::SetFixedSize);

設定主視窗的Layout的長寬為sizeHint (),且不能被改變~

myLineEdit->setMinimumWidth (fm.width (myLineEdit->text ()));

這裡是根據QLineEdit所輸入的內容來決定QLineEdit的最小寬度是多少,
另外,要注意的是,用text ().size ()是回傳有幾個字元,但是,setMinimumWidth是要輸入要幾個pixel,因此,必需由目前使用的字型來決定幾個字元需要多少個pixel。

本程式會把使用者輸入的字串長度轉成pixel,並且設定為QLineEdit的最小長度。
當最小長度大於原本的sizeHint的時候,sizeHint就會被重新設定為MinimumWidth的寬度。
而layout則是根據sizeHint來調整MyWidget的小大~

因此,QLineEdit的寬度會保持在
QLineEdit::sizeHint() ~ fm.width (myLineEdit->text ())

在還沒有輸入任何資料前的樣子


在選擇完檔案或資料夾時,主視窗會自動變大~


在經過這個sample code後,若某一個元件是有被Layout來管理的話,要調整他的大小,沒有辦法直接設定他的大小,必需
1. 設定Layout的policy
2. 設定Widget本身的policy,其最大、最小的寬度
那麼Qt layout manager就可以跟據這一些資料來調整Widget最適合的大小。

參考資料:
QFontMetrics Class Reference
Measuring text width in Qt
QBoxLayout與QWidget之間的關係

2011年10月21日 星期五

Qt - 選擇資料夾或特定的檔案

目前打算做一個小程式,可以讓使用選擇特定的檔案或資料夾

main.cpp

#include <QApplication>
#include "MyWidget.h"

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

MyWidget myWidget;

myWidget.show ();

return app.exec ();
}


MyWidget.h
#ifndef _MY_WIDGET_H_
#define _MY_WIDGET_H_

#include <QWidget>

class QLabel;
class QPushButton;
class QLineEdit;

class MyWidget : public QWidget {
Q_OBJECT

public:
MyWidget (QWidget *parent = 0);

private slots:
void browse ();

private:
QLabel *myLabel;
QPushButton *myPushButton;
QLineEdit *myLineEdit;
};

#endif //#ifndef _MY_WIDGET_H_


MyWidget.cpp
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QFileDialog>

#include "MyWidget.h"

MyWidget::MyWidget (QWidget *parent) : QWidget (parent) {
// do nothing
myLabel = NULL;
myLineEdit = NULL;
myPushButton = NULL;

myLabel = new QLabel (tr ("Target Name"), this);

myLineEdit = new QLineEdit (this);

myPushButton = new QPushButton (tr ("&Browse..."), this);

connect (myPushButton, SIGNAL (clicked ()), SLOT (browse ()));

QHBoxLayout *layout = new QHBoxLayout (this);
layout->addWidget (myLabel);
layout->addWidget (myLineEdit);
layout->addWidget (myPushButton);

this->setLayout (layout);
}

void MyWidget::browse () {
// QString directory = QFileDialog::getExistingDirectory (this, tr ("Find Files"), QDir::currentPath ());

QFileDialog myFileDialog (this);
QString itemPath = myFileDialog.getOpenFileName (this, tr ("Open File"), QDir::currentPath (), tr ("All C++ files (*.cpp *.h)"));
if (itemPath.isEmpty ()) {
myLineEdit->setText (myFileDialog.directory ().absolutePath ());
} else {
myLineEdit->setText (itemPath);
}
}

結果如下圖所示


本來打算只利用QFileDialog::getOpenFileName ()就可以選擇檔案和資料夾~
就是當使用者沒有選擇檔案的時候,同時按下「開啟」,這樣就會選擇目前視窗的路徑~
但是,沒有選擇檔案的時候,按開啟並不會回傳值。所以,只好讓使用都可以選擇目前要選擇檔案還是資料夾。
sample code如下:
main.cpp
#include <QApplication>
#include "MyWidget.h"

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

MyWidget myWidget;

myWidget.show ();

return app.exec ();
}

MyWidget.h
#ifndef _MY_WIDGET_H_
#define _MY_WIDGET_H_

#include <QWidget>

class QLabel;
class QPushButton;
class QLineEdit;

class MyWidget : public QWidget {
Q_OBJECT

public:
MyWidget (QWidget *parent = 0);

private slots:
void browse ();
void ChangeSelectFile (bool);

private:
QLabel *myLabel;
QPushButton *myPushButton;
QLineEdit *myLineEdit;
bool SelectFile;
};

#endif //#ifndef _MY_WIDGET_H_

MyWidget.cpp
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QGroupBox>
#include <QRadioButton>

#include "MyWidget.h"

MyWidget::MyWidget (QWidget *parent) : QWidget (parent) {

//
// init
//

myLabel = NULL;
myLineEdit = NULL;
myPushButton = NULL;

//
// Create Label component
//

myLabel = new QLabel (tr ("Target Name"), this);

//
// Create LineEdit component
//

myLineEdit = new QLineEdit (this);

//
// Create GroupBox and RadioButton component
//

QGroupBox *box = new QGroupBox (tr ("Select Type"));
QRadioButton *radio1 = new QRadioButton (tr ("File"));
QRadioButton *radio2 = new QRadioButton (tr ("Directory"));

//
// Set the default checked RadioButton for SelectFile
//

radio1->setChecked (true);
SelectFile = true;

//
// Set RadioButton into QHBoxLayout
// And set RadioButton into same GroupBox
//

QVBoxLayout *VLayout = new QVBoxLayout;
VLayout->addWidget (radio1);
VLayout->addWidget (radio2);
box->setLayout (VLayout);

//
// Create QPushButton component
//

myPushButton = new QPushButton (tr ("&Browse..."), this);

//
// Add all the components into QHBoxLayout
//

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget (myLabel);
layout->addWidget (myLineEdit);
layout->addWidget (box);
layout->addWidget (myPushButton);

//
// Set the main Layout for MyWidget
//

this->setLayout (layout);

//
// Set the SIGNAL and SLOT for this component
//

connect (myPushButton, SIGNAL (clicked ()), SLOT (browse ()));
connect (radio1, SIGNAL (toggled (bool)), this, SLOT (ChangeSelectFile (bool)));
}

void MyWidget::browse () {

QString TargetItem;

QFileDialog myFileDialog (this);
if (SelectFile) {
TargetItem = myFileDialog.getOpenFileName (this, tr ("Open File"), QDir::currentPath (), tr ("All C++ files (*.cpp *.h)"));
} else {
TargetItem = myFileDialog.getExistingDirectory (this, tr ("Select Folder"), QDir::currentPath ());
}
if (TargetItem.isEmpty ()) {
// myLineEdit->setText (myFileDialog.directory ().absolutePath ());
// myLineEdit->clear ();
} else {
myLineEdit->setText (TargetItem);
}
}

void MyWidget::ChangeSelectFile (bool checked) {
SelectFile = checked;
}


設定為選擇File:

當按Browse後,會出現以下的視窗,並且選擇一個限定的副檔名的檔案

當按下開啟後,會把選擇的檔案的路徑放在QLineEdit component裡面


另外,若選擇Directory的話,並且選擇Browse,會跳出以下的視窗


當按下確定後,就會把資料夾的路徑放在QLineEdit裡面,如下圖所示


參考資料:
QFileDialog Class Reference
Widgets and Layouts
Qt 第二章 创建对话框--子类化QDialog
QRadioButton Class Reference
QAbstractButton Class Reference
QLineEdit Class Reference

2011年10月18日 星期二

Advanced Format Driver

在2011年1月後出的硬碟都會支援Advanced Format
原本的硬碟都是採用512 byte為一個chunk,
在Advanced Format是採用4k為一個chunk。

聽說在XP上使用這一個硬碟的話,會有很多問題~
目前可能還是不打算使用這一種新的硬碟~

參考資料:
已經來臨的硬碟格式變動 先進格式
體驗最新 WD 先進格式化技術硬碟!

放棄XP系統 WD硬盤先進格式化使用要點
先進格式化

2011年10月13日 星期四

在Qt下呼叫外部指令

這裡透過Qt的QProcess來呼叫外部程式,並且把結果顯示在QTextEdit
main.cpp

#include <QApplication>
#include <QTextEdit>
#include <QProcess>

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

QTextEdit *TextEdit = new QTextEdit;

TextEdit->show ();

QProcess *proc = new QProcess;

// proc->startDetached ("ping 168.95.1.1");
proc->start ("ping 168.95.1.1");

if (proc->waitForFinished (-1)) {
TextEdit->append (proc->readAll ());
} else {
TextEdit->append ("Error");
}

return app.exec ();
}

不過,以上的程式有一個缺點,就是只有當外部指令結束之後,才會把結果顯示在QTextEdit裡面,這個時候會造成畫面當掉的感覺~

透過processEvent ()
可以適時的更新Qt的畫面~
但是仍會頓頓的~
main.cpp
#include <QApplication>
#include <QTextEdit>
#include <QProcess>

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

QTextEdit *TextEdit = new QTextEdit;

TextEdit->show ();

QProcess *proc = new QProcess (TextEdit);

int x = 0;


// proc->startDetached ("ping 168.95.1.1 -t");
proc->start ("ping 168.95.1.1 -t");

while (proc->state () == QProcess::Running) {
x++;
// while (1) {
if (proc->waitForReadyRead (-1)) {
if (x == 10) {
proc->close ();
break;
}
TextEdit->append (proc->readAll ());
app.processEvents ();
} else {
TextEdit->append ("Error");
}
}

return app.exec ();
}


最後,透過sign與slot,當有資料可讀的時候,才去讀資料,終於解決會頓頓的情況了。
以下是sample code
MyTextEdit.h
#ifndef _MY_TEXT_EDIT_H_
#define _MY_TEXT_EDIT_H_

#include <QTextEdit>

class QProcess;

class MyTextEdit : public QTextEdit {
Q_OBJECT

public:
MyTextEdit (QWidget *parent = 0);
void StartCmd ();

public slots:
void AppendContextFromStandOut ();
void AppendContextFromStandErr ();
void AppendContext ();

private:
QProcess *MyProc;
};

#endif //#ifndef _MY_TEXT_EDIT_H_


MyTextEdit.cpp
#include "MyTextEdit.h"
#include <QProcess>

MyTextEdit::MyTextEdit (QWidget *parent) : QTextEdit (parent) {
// do nothing
}

void MyTextEdit::AppendContextFromStandOut () {
this->append (MyProc->readAllStandardOutput ());
}

void MyTextEdit::AppendContextFromStandErr () {
this->append (MyProc->readAllStandardError ());
}

void MyTextEdit::AppendContext () {
this->append (MyProc->readAll ());
}

void MyTextEdit::StartCmd () {

MyProc = new QProcess (this);

// connect (MyProc, SIGNAL(readyReadStandardOutput ()), this, SLOT(AppendContextFromStandOut ()));
// connect (MyProc, SIGNAL(readyReadStandardError ()), this, SLOT(AppendContextFromStandErr ()));
connect (MyProc, SIGNAL(readyRead ()), this, SLOT(AppendContext ()));

MyProc->start ("ping 168.95.1.1 -t");
}


main.cpp
#include <QApplication>
#include "MyTextEdit.h"

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

MyTextEdit *TextEdit = new MyTextEdit;

TextEdit->show ();

TextEdit->StartCmd ();

return app.exec ();
}

最後輸出如下

原版的如下:


耶,怎麼多出那麼多空白行呢?
為了去了解,輸出的內容是什麼,使用一個很好用的函式QByteArray::toHex ()
有以下三點發現
1. Qt還是使用Unix換行的方式,只有0x0a("\n");而在Windows下的換行為0x0a("\r"),0x0d("\n")。因此,必需要移除掉多餘的0x0d
2. 我們由QProcess讀取出來的output本身就有換行符號(0x0a),而每做一個QTextEdit::append ()前,也會跳到新的一行,因此,QTextEdit::append ()多的這一個換行就變成是多餘的了~所以,必需用QTextEdit::insertPlainText ()來取代
3. 因為,QTextEdit::insertPlainText ()是由目前鼠標的位置直接加入字串。所以必需另外,把QTextEdit設定為disable,避免讓使用著移動滑鼠來改變鼠標的位置。
只需要修改MyTextEdit.cpp,程式碼如下:
#include "MyTextEdit.h"
#include <QProcess>
#include <QChar>

MyTextEdit::MyTextEdit (QWidget *parent) : QTextEdit (parent) {
this->setEnabled (false);
}

void MyTextEdit::AppendContextFromStandOut () {
this->append (MyProc->readAllStandardOutput ());
}

void MyTextEdit::AppendContextFromStandErr () {
this->append (MyProc->readAllStandardError ());
}

void MyTextEdit::AppendContext () {

QByteArray TempByteArray(MyProc->readAll ());

QString TempString(TempByteArray);

TempString.remove (QChar(0x0d));

// this->append (TempByteArray.toHex ());
// this->append (TempString);
this->insertPlainText (TempString);

}

void MyTextEdit::StartCmd () {

MyProc = new QProcess (this);

// connect (MyProc, SIGNAL(readyReadStandardOutput ()), this, SLOT(AppendContextFromStandOut ()));
// connect (MyProc, SIGNAL(readyReadStandardError ()), this, SLOT(AppendContextFromStandErr ()));
connect (MyProc, SIGNAL(readyRead ()), this, SLOT(AppendContext ()));

MyProc->start ("ping 168.95.1.1");
}

結果如下:


但是,直接把0x0d("\r")這字元移除掉,看起來不是很好的辦法,理論上應該是把"\r\n"直接取代成"\n"比較合理
修改MyTextEdit.cpp結果如下:
#include "MyTextEdit.h"
#include <QProcess>
#include <QChar>

MyTextEdit::MyTextEdit (QWidget *parent) : QTextEdit (parent) {
this->setEnabled (false);
}

void MyTextEdit::AppendContextFromStandOut () {
this->append (MyProc->readAllStandardOutput ());
}

void MyTextEdit::AppendContextFromStandErr () {
this->append (MyProc->readAllStandardError ());
}

void MyTextEdit::AppendContext () {

QByteArray TempByteArray(MyProc->readAll ());

QByteArray WinNewLine ("\r\n"), UnixNewLine ("\n");

TempByteArray.replace (WinNewLine, UnixNewLine);

QString TempString(TempByteArray);

// this->append (TempByteArray.toHex ());
// this->append (TempString);
this->insertPlainText (TempString);

}

void MyTextEdit::StartCmd () {

MyProc = new QProcess (this);

// connect (MyProc, SIGNAL(readyReadStandardOutput ()), this, SLOT(AppendContextFromStandOut ()));
// connect (MyProc, SIGNAL(readyReadStandardError ()), this, SLOT(AppendContextFromStandErr ()));
connect (MyProc, SIGNAL(readyRead ()), this, SLOT(AppendContext ()));

MyProc->start ("ping 168.95.1.1");
}


在繼續補足其它功能的時候,意外發現,我已經把視窗關掉了,為什麼我執行的外部指令還在執行哩~

原因就是,我在main.cpp裡面是宣告一個MyTextEdit的指標變數,並且指到我建立的記憶體空間(new QTextEdit),當主程式關掉之後,MyTextEdit的指標變數會release給系統(因為,存活的範圍只有在main的{}裡面),但是,MyTextEdit建立的記憶體空間就不會release給系統,除非delete掉這一個空間。

要解決一個方法,就是在main.cpp裡面,宣告一個物件而不是宣告一個指標來指到一個要求的記憶體位址。
main.cpp
#include <QApplication>
#include "MyTextEdit.h"

int main (
int argc,
char *argv[]
)
{
QApplication app (argc, argv);

MyTextEdit TextEdit;

TextEdit.show ();

TextEdit.StartCmd ();

return app.exec ();
}

MyTextEdit.h
#ifndef _MY_TEXT_EDIT_H_
#define _MY_TEXT_EDIT_H_

#include <QTextEdit>

class QProcess;

class MyTextEdit : public QTextEdit {
Q_OBJECT

public:
MyTextEdit (QWidget *parent = 0);
void StartCmd ();
bool IsScrollDown ();

public slots:
void AppendContext ();
void MoveScrollDown ();

private:
QProcess *MyProc;
};

#endif //#ifndef _MY_TEXT_EDIT_H_

MyTextEdit.cpp
#include "MyTextEdit.h"
#include <QProcess>
#include <QChar>
#include <QScrollBar>
#include <QDebug>

MyTextEdit::MyTextEdit (QWidget *parent) : QTextEdit (parent) {
MyProc = NULL;
setReadOnly (true);
// setTextInteractionFlags (textInteractionFlags() & Qt::NoTextInteraction);
// setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
}

void MyTextEdit::AppendContext () {

bool KeepDownScroll = false;

int OrgScrollBarValue = 0;

//
// Get the output string
//

QByteArray AppendByteArray(MyProc->readAll ());

//
// Get the original ScrollBar value
//

OrgScrollBarValue = verticalScrollBar ()->value ();

QByteArray WinNewLine ("\r\n"), UnixNewLine ("\n");

//
// Replace "\r\n" by "\n"
//

AppendByteArray.replace (WinNewLine, UnixNewLine);

QString AppendString(AppendByteArray);

// this->append (AppendByteArray.toHex ());

if (IsScrollDown ()) {
if (!(textCursor ().hasSelection () || textCursor ().hasComplexSelection())) {
//
// When user select some range or the scroll is already under the buttom
// set the scroll under the buttom
//

KeepDownScroll = true;
}
}

//
// In order to append string in the end of text
// have to get the end cursor of the text
// After append the string, return the cursor to the original status
//

QTextCursor EndCursor, OriginalCursor;
EndCursor = OriginalCursor = textCursor ();
EndCursor.movePosition (QTextCursor::End);
setTextCursor (EndCursor);

//
// Append the string in the end of text
//

insertPlainText (AppendString);

//
// return the cursor to the original status
//

setTextCursor (OriginalCursor);

//
// Set the scrollbar value be the original value
//

QScrollBar *ScrollBar = verticalScrollBar ();
ScrollBar->setValue (OrgScrollBarValue);

//
// When user select some range or the scroll is already under the buttom
// set the scroll under the buttom
//

if (KeepDownScroll) {
MoveScrollDown ();
}

}

void MyTextEdit::StartCmd () {

MyProc = new QProcess (this);

connect (MyProc, SIGNAL(readyRead ()), this, SLOT(AppendContext ()));

MyProc->start ("ping 168.95.1.1 -t");
}

void MyTextEdit::MoveScrollDown () {

// Method 1
// QTextCursor c = textCursor ();
// c.movePosition (QTextCursor::End);
// setTextCursor (c);

// Method 2
QScrollBar *ScrollBar = verticalScrollBar ();
ScrollBar->setValue (ScrollBar->maximum ());

}

bool MyTextEdit::IsScrollDown () {

QScrollBar *ScrollBar = verticalScrollBar ();

if (ScrollBar->value () == ScrollBar->maximum ()) {
return true;
} else {
return false;
}
}


結果如下:
1. 當原本右邊的ScrollBar原本就在底部的話,就算文字內容增加,ScrollBar仍會保持在底部

2. 當使用者有圈選內容的話,就算文字內容增加,ScrollBar會保持在原來的位置,若原本的ScrollBar是在底部的話,會因為文字內容增加,而讓ScrollBar離開底部

3. 當使用者移動ScrollBar離開底部時,當文字內容增加,ScrollBar仍會保持在原來的位置。但當使用者把ScrollBar拉回底部時,當文字內容增加,ScrollBar會依然保持在底部。


參考資料:
QT下实现对linux 的Shell 调用 的几种方法 QProcess AND QThread
QTextEdit Class Reference
QProcess Class Reference
QProcess运行外部程序
怎么处理QT的UI界面假死的情况
QT程序 避免假死、无反应现象
QT中使用QProcess启用外部程序||exe
关于窗口调用外部程序及接收返回内容的调试
QT下解决换行符、回车符与Windows不一致的问题
解决QProcess對象調用execute執行cmd命令不支持中文和空格的問題
VCard
Qt - QTextEdit自動捲到底
QT中使用QProcess启用外部程序

2011年10月12日 星期三

夢想

如果對夢想沒有熱情,
所有與它相關的事物也不可能有熱情。
要完成夢想,
取決於你有多少熱情,
如果我們對夢想的喜愛,
沒有到癡狂的地步,
就會非常容易放棄。