QRegExp regExp("[a-zA-Z][1-9][0-9]{0,2}"); xxx->setValidator(new QRegExpValidator(regExp,this)); lineEdit->setValidator(new QRegExpValidator(regExp,this));
connect(objectA,SIGNAL(methodA()),objectB,SLOT(methodB())); //methodA()的輸入參數能夠比methodB()的參數多
lineEdit->hasAcceptableInput(); //返回true or false lineEdit->setText("please input text"); button->setEnabled(true); //set true or false
class A { Q_OBJECT signals: void funs(type A,type B); //定義信號函數 }; type a;type b; emit funs(a,b); //發射上面定義的信號函數 ,固然須要使用QObjetc::connect()這個函數 把這個信號函數與真實的slot函數綁定起來,slot函數纔是真正幹活的函數
QTabWidget QListWidget 和 QStackedWidget 配合使用 QTreeWidget 和 QStackedWidget 配合使用
//隱藏必要的子Widget xx->hide(); yy->hide(); //下面這個方法很是關鍵,會根據xx,yy子widget是否顯示,動態調整窗口的大小 layout()->setSizeConstraint(QLayout::SetFixedSize);
class MyClass: pulbic QObject { public: MyClass(const string& text,QObject *parent=0); }; MyClass::MyClass(const string& text,QObject *parent): QObject(parent) { //構造函數的定義 }
QList<QString> list; list<<"foo"<<"bar"<<"baz"; foreach(QString a,list) qDebug()<<a; #至關好用的QList QList<QString> list; list << "first"; list.append( "second" ); list.prepend( "third" ); list.insert( 1, "fourth" ); list.insert( 4, "fifth" );
QList<int> list; list << 23 << 27 << 52 << 52; QListIterator<int> javaIter( list ); while( javaIter.hasNext() ) qDebug() << javaIter.next(); QList<int>::const_iterator stlIter; for( stlIter = list.begin(); stlIter != list.end(); ++stlIter ) qDebug() << (*stlIter);
QList<int> list; list << 27 << 33 << 61 << 62; QMutableListIterator<int> javaIter( list ); while( javaIter.hasNext() ) { int value = javaIter.next() + 1; javaIter.setValue( value ); qDebug() << value; } QList<int>::Iterator stlIter; for( stlIter = list.begin(); stlIter != list.end(); ++stlIter ) { (*stlIter) = (*stlIter)*2; qDebug() << (*stlIter); }
button: QPushButton QToolButton QRadioButton box: QCheckBox QGroupBox QToolBox QSpinBox QDoubleSpinBox QComboBox edit: QLineEdit QTextEdit QDateEdit QTimeEdit QDateTimeEdit widget: QTabWidget view: QListView QTreeView QTableView dialog: QInputDialog QProgressDialog QColorDialog QFontDialog QPageSetupDialog QFileDialog QPrintDialog others: QFrame QLabel QLCDNumber QProgressBar QTextBrowser QSlider QDial QMessageBox QErrorMessage
#1 阻塞式:(主窗口的內容是沒法訪問的) QDialog dialog; Ui_Dialog a; a.setupUi(&dialog); if(dialog.exec()) // 當點下ok button時會返回accept=true,當點下cancel時會返回reject=0 { } #2 非阻塞式:(訪問子dialog的同時,也能訪問父窗口) findDialog=new FindDialog(this); connect() //把finddialog的信息 傳遞給接受信息,處理信息的槽函數 findDialog->show(); findDialog->raise(); findDialog->activateWindow();
QTableWidget * spreadsheet=new QTableWidget(this); setCentralWidget(spreadsheet);//這個方法是QMainWindow的方法 #獲得當前鼠標focus的單元格的行座標和列座標 spreadSheet->currentRow() spreadSheet->currentColumn() #獲得當前單元格的內容 //若是當前單元格內沒有內容,if內容爲NULL if(spreadSheet->currentItem()) { cout<<spreadSheet->currentItem()->text()<<endl; } #鼠標focus的單元格位置發生變化時,觸發以下信號函數 currentCellChanged(int,int ,int,int)
setWindowTitle(); setWindowIcon(QIcon("xx.png")); #在QMainWindow中如何添加菜單欄和工具欄 #建立須要 action newAction=new QAction("&new",this); newAction.setIcon(QIcon("xx.png")); connect(newAction,SIGNAL(),object,SLOT()); //讓action幹相應的活 #添加一個菜單欄 QMenu *fileMenu=menuBar()->addMenu("&File"); fileMenu->addAction(neAction); fileMenu->addSeparator(); #添加一個QToolBar QToolBar * fileToolBar= addToolBar("&file"); fileToolBar->addAction(newAction); fileToolBar->addSeparator(); //menufile->addSeparator()這個函數也是返回一個QAction *類型的數據 #在statusBar()中添加widget statusBar()->addWidget(label); statusBar()->addWidget(label,1); //從左開始放label,1表示用空白擴展剩下的右邊空間 statusBar()->showMessage(const QString & str);
QLabel * label=new QLabel("w999"); label->setAlignment(Qt::AlignHCenter);//文字對齊方式 label->setMinimumSize(label-sizeHint());//文字寬度最少4個字符,當QLabel中沒有字符時,也會保證最少有4個字符的空白位置顯示
#建立settings對象 QSettings settings("Yzs_think", "Application"); 公司或組織名稱:Yzs_think, 程序名稱:Application #從settings中讀出數據,設置應用程序的相關參數,能夠設置默認值 QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(400, 400)).toSize(); resize(size); move(pos); #程序退出前,把須要保存的參數保存到settings中,書上說是保存到註冊表中去了,尚未實踐過 QSettings settings("Yzs_think", "Application"); settings.setValue("pos", pos()); settings.setValue("size", size());
#保證容器一直在top layer(就是經常使用的fix 窗口在頂層) w.setWindowFlags(Qt::WindowStaysOnTopHint);
//event函數被調用,分爲下面幾種狀況: 1:用戶對mouse and keyboard的操做 2:定時器時間到了 3:網絡超時 4:窗口管理器 1:上面是4類稱爲event sources,事件產生的源頭 2:event object:這個就是包含事件源有何種改變的事件對象( 如QPressedEvent *e) 3:event target,這處就是事件會通知給誰(通常就是事件處理函數) 一句話說:event sources發生的事件變化,包裝到event object中,傳遞給event target //窗口大小發生變化時,或是鼠標從一個widget到另外一個widget時移動時, 程序啓動時會在構造函數調用調用以後,調用 paintEvent函數(參數類型不能寫錯) void paintEvent(QPaintEvent *) //點了右上角的x時,會調用該方法 void closeEvent(QCloseEvent *)
qt中的主窗口是是沒有父窗口的 有父窗口的widget,稱爲子部件 Qt::WindowFlags做爲父窗口的第二個參數,能夠定義父窗口不少重要屬性:以下 Qt::Widget Qt::Dialog Qt::SplashScreen #保證容器一直在top layer(就是經常使用的fix 窗口在頂層) w.setWindowFlags(Qt::WindowStaysOnTopHint); #函數對窗口進行最大,最小化,全屏操做 setWindowState() #對於主窗口,咱們很是關心窗口的大小和出現的位置,下面的函數是getter, 主窗口包含兩部分: 1:框架部分(如title and border):使用x(),y(),pos(),move(),frameGeometry()函數訪問 2:內容部分,稱爲無框架的窗口:使用width(),height(),geometry(),setGeometry(),Rect(),Size()函數訪問 ,resize()函數是調整內容部分的大小。 綜上:使用move(),setGeometry()兩個函數設置窗口出如今桌面的位置和窗口的長寬。 w.setGeometry(QRect(0,0,400,400));//這裏的0,0,是.geometry().x() .y()的值設置爲0 w.move(0,0);//這裏的0,0是pos().x() .y()的值設置爲0 #setFixedSize(size.Hint())//固定主窗口的大小爲不可改變 一般以下,設置父窗口的大小位置 w.setGeometry(QRect(0,0,400,400)); w.move(0,0); #w.frameGeometry() 這個是外邊框的信息 .x() .y() .width() .height() #w.geometry() 是內部內容部分的信息 .x() .y() .width() .height() .resize(w,h)函數 調整大小,是內容部分的寬高 This property holds the size of the widget excluding any window frame.
在程序代碼行號前單擊,肯定斷點,再點擊,取消斷點 按F5,程序進入斷點調試過程,比較慢,不是大的問題,不須要用這樣的方法調試,太耗費資源時間了 斷點的好處就是方便的觀察變量的值
geometry : QRect This property holds the geometry of the widget relative to its parent and excluding the window frame. frameGeometry : const QRect This property holds geometry of the widget relative to its parent including any window frame.
指明瞭父窗口的子widget,能夠不用顯式的delete掉,父窗口會處理好後面的垃圾回收工做java
模態窗口與模態窗口(根據須要進行選擇show() or exec())web
另外一種實現modal態的方法:(阻塞態) (這種方法可使窗口爲阻塞態的同時,程序還能夠處理其它的事情,由於調用 了show()以後,控制權就給調用者了) QDialog *d=new QDialog(this); d->setModal(true); d->show(); setWindowModality(xx)://xx可取下三值 : Qt::NonModal :不阻塞 Qt::WindowModal :阻塞父,祖窗口,和他們的子窗口 Qt::ApplicationModal :阻塞全部窗口,setModal(true)就是達到這一效果
signal and slot的做用是完成對象之間協同工做,如信息的傳遞,事件的響應 close() 槽通常是隱藏窗口,只有當 當前widget是最後一個窗口時,纔會delete掉 Closes this widget. Returns true if the widget was closed; otherwise returns false. First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event. If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not. The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.
#1: 顏色對話框 QColor color=QColorDialog::getColor(Qt::red,this,tr("顏色對話框")); QColor color=QColorDialog::getColor(Qt::red,this,tr("顏色對話框"),QColorDialog::ShowAlphaChannel);//能夠設置顏色的alpha值 #2: 顏色對話框 QColorDialog dialog(Qt::red,this); dialog.setOption(QColorDialog::ShowAlphaChannel); dialog.exec(); QCoolor color=dialog.currentColor(); #3: 文件對話框 返回的是包含絕對路徑的文件名 QString fileName=QFileDialog::getOpenFileName(this,tr("文件對話框"),"D:",tr("圖片文件(*.png *.jpg)")); #4:文件對話框 返回多個文件名 QStringList fileNames=QFileDialog::getOpenFileNames(this,tr("文件對話框"),"D:",tr("圖片文件(*.png *.jpg)")); #5: 文件對話框(保存文件,另存) QFileDialog::getSaveFileName(); #6: 獲得已存在文件夾的路徑 QFileDialog::getExistingDirectory(); #7:獲得字體對話框(設置對象字體時須要) bool ok; QFont font=QFontDialog::getFont(&ok,this) if(ok) { //yes u select a font xx->setFont(font);![圖片描述][1] } else { } #8:獲得用戶輸入對話框:QInputDialog QInputDialog::getText(xx); QInputDialog::getInt(xx); QInputDialog::getDouble(xx); QInputDialog::getItem(xx); #9信息對話框 :QMessageBox QMessageBox::information(); QMessageBox::quesiton(); QMessageBox::warning(); QMessageBox::critical(); QMessageBox::about();
QWizardPage * createPage() { QWizardPage * page=new QWizardPage; page.setTitle("開始學習"); return page; } QWizard *wizard=new QWizard(this); wizard->setWindowTitle("軟件使用指南"); wizard->addPage(createPage()); wizard->exec(); delete wizard;
QPageSetupDialog --- QPrintDialog --- QPrintPreviewDialog正則表達式
#QString QString a="hello"; QString b="world"; QString c=a+" "+b; c.append(" ok"); c.prepend("head "); QString::number(string.size()); string.toUpper(); string.toLower(); #目前使用Qt的版本 qVersion();//return char * #Qt的標準輸出流 QTextStream out(stdout); out << "console application\n"; #Qt文件的寫入 QFile data("filename"); if (data.open(QFile::WriteOnly)) { QTextStream out(&data); out << "You make me want to be a better man." << endl; } #Qt文件的讀出 QFile data("filename"); QString line; if (data.open(QFile::ReadOnly)) { QTextStream in(&data); in.setCodec("UTF-8"); //設置utf文件編碼 do { line=in.readLine(); }while(!line.isEmpty()); } #QList QTextStream out(stdout); QList<QString> list; list << "Balzac" << "Tolstoy" << "Guldbrassen" << "London" << "Galsworthy" << "Sienkiewicz"; qSort(list); for (int i = 0; i < list.size(); ++i) { out << list.at(i) << endl; } #QDir QTextStream out(stdout); QString home = QDir::homePath(); out << home << endl; #獲得某一目錄下的特定類型文件名 QTextStream out(stdout); QDir dir; QStringList filters; filters << "*.c" << "*.c~"; //對不須要的文件進行過慮 dir.setNameFilters(filters); QFileInfoList list = dir.entryInfoList(); for (int i=0; i<list.size(); ++i) { QFileInfo fileInfo = list.at(i); out << QString("%1").arg(fileInfo.fileName()); /文件名在這裏 out << endl; } #QTime QTime qtime = QTime::currentTime(); QString stime = qtime.toString(Qt::LocalDate);
QHBoxLayout * hlayout =new QHBoxLayout(); hlayout->addWidget(QWidget *, int stretch=0,Qt::Alignment alignment=0); QGridLayout * glayout =new QGridLayout(); glayout->addWidget(QWidget *,int row, int col,int rowspan=1,int colspan=1,Qt::Alignment alignment=0); QFormLayout QStackedLayout
sizeHint(); minimumSizeHint(); 對於每一個widget,都有這兩個函數,用來保存部件的建議大小尺寸和最小大小尺寸 當咱們使用了下面的函數,設置了最小大小後,就不會用minimumSizeHint的大小了 pushButton->setMinimumSize(); setSizePoliy()這個函數對於設置widget的尺寸大小很是重要 下面的函數用來 讀取 和 設置 widget的sizePolicy屬性 pushButton->sizePolicy(); pushButton->setSizePolicy(QSizePolicy::Policy horizontal QSizePolicy::Poliyc vertical ); QSizePolicy的取值有: QSizePolicy::Minimum :sizeHint提供的值是最小的尺寸 QSizePolicy::Maximum :sizeHint提供的值是最大的尺寸 QSizePolicy::Fixed :只能使用sizeHint的值,也可以使用setFixedSize函數定死widget的大小 QSizePolicy::Expanding :最合適的大小爲sizeHint,可是可壓縮,不過傾向於expanding QSizePolicy::Preferred :最合適的大小爲sizeHint,可升可縮 QSizePolicy::MinimumExpanding :sizeHint提供的值是最小的尺寸,傾向於expanding QSizePolicy::Ignored ;不考慮sizeHint的值,有多大變多大 #使用例子 QSizePolicy policy ; policy.setHorizontalStretch(1); policy.setVerticalStretch(1); policy.setHorizontalPolicy(QSizePolicy::Minimum); button->setSizePolicy(policy); pushButton3->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
QString filename="/abc/9.jpg"; QFileInfo qfile(filename); qcout<<qfile.baseName()<<endl; // 9 qcout<<qfile.absoluteFilePath()<<endl; // /abc/9.jpg qcout<<qfile.absoluteDir().absolutePath()<<endl; /abc qcout<<qfile.completeSuffix()<<endl; //jpg qcout<<qfile.fileName()<<endl; //9.jpg #實用小例子: QString filename="/root/abc/10.jpg"; QFileInfo qfile(filename); QString extension=qfile.completeSuffix(); //獲得後綴jpg QString absoluteFnNoExtension=QString(filename).remove("."+extension);// 去除後綴 /root/abc/10 QString alphaname=absoluteFnNoExtension+"_alpha."+extension; //產生其它須要的文件名
QString one="11.jpg"; QString two="22.jpg"; QString three="33.ddd"; //這一步是必須要的,沒有這個中間過程會產生問題 string cone=one.toStdString(); string ctwo=two.toStdString(); string cthree=three.toStdString(); const char *pone=cone.c_str(); const char *ptwo=ctwo.c_str(); const char *pthree=cthree.c_str();
##日期時間格式化字符串,也是比較容易的(要懂英語哦) ###以顯示年爲例,一般咱們的年份都是4個數字,year是年的單詞 ###那麼用yyyy就表示年的佔位符 ###有個問題:月month的佔位符和分鐘minute的佔位符都是mm??怎麼辦 ###解決辦法是月的佔位符用M,分鐘的佔位符用mm ###理解了上面的原則後,就不須要死記硬背了哦 QDateTime nowDateTime=QDateTime::currentDateTime(); //QString nowDateTimeStr=nowDateTime.toString("yyyy-M-dd hh:mm:ss"); QString nowDateTimeStr=nowDateTime.toString("yyyy/M/dd hh:mm:ss"); ui->dateTimeLabel->setText(nowDateTimeStr);
QSignalMapper * mapper=new QSignalMapper(this); mapper->setMapping(button0,"0"); mapper->setMapping(button1,"1"); ... connect(button0,SIGNAL(clicked()),mapper,SLOT(map())); connect(button1,SIGNAL(clicked()),mapper,SLOT(map())); connect(mapper,SIGNAL(mapped(QString)),this,SLOT(buttonClicked(QString))); #工做方法: #當button0發生clicked()信號後,會調用map()槽 #map()曹函數會根據setMapping裏面設置的QString,發送一個mapped(QString)信號 #而後這樣就會調用 buttonClicked(QString)這個槽函數,根據QString的數據, #就能夠知道用戶點擊了哪一個按鍵! #當有不少button,而且但願在一個槽函數中,處理全部clicked事件時,可使用 #QSignlaMapper實現
#Qt中常常須要隱藏原生的最大最大小化按鈕,而後定製本身的最大,最小化方式,下面是經常使用的方法 #在構造函數中使用以下函數 setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //無原生框架,最前端顯示 setAttribute(Qt::WA_TranslucentBackground, true); //若是須要主窗口背景透明,調用這個函數 #若是須要設置主窗口的背景顏色和透明的程度,能夠在paintEvent函數中調用以下函數 : QPainter painter(this); painter.fillRect(this->rect(), QColor(255, 255, 255, 0)); //前三個數值爲顏色,最後一個值爲alpha通道,便是透明程度(0全爲背景全透明,即看到不背景) #注意,看調用 setAttribute(Qt::WA_TranslucentBackground, true);函數後,背景默認是全透明的!
#paintEvent事件處理函數中,使用以下方式實現 QBitmap bmp(ui->frame->size()); bmp.fill(); QPainter p(&bmp); p.setBrush(Qt::black); p.setRenderHint(QPainter::Antialiasing); //抗鋸齒 p.drawRoundedRect(bmp.rect(), 5, 5); //四個角都是圓弧 //只要上邊角圓弧 int arcR = 5; //弧度 QRect rect = this->rect(); // QPainterPath path; // //逆時針 // path.moveTo(arcR, 0); // path.arcTo(0, 0, arcR * 2, arcR * 2, 90.0f, 90.0f); // path.lineTo(0, rect.height()); // path.lineTo(rect.width(), rect.height()); // path.lineTo(rect.width(), arcR); // path.arcTo(rect.width() - arcR * 2, 0, arcR * 2, arcR * 2, 0.0f, 90.0f); // path.lineTo(arcR, 0); // p.drawPath(path); // p.fillPath(path, QBrush(Qt::Red)); //arm和windows平臺沒有這行代碼將顯示一個透明的空空的框 ui->frame->setMask(bmp);
#對於一個不大的項目,一到兩我的維護時,把全部Widgets的樣式放到一個qss文件中,是理想的選擇 #設置方法若是,在Qt designer中preview樣式後(alt+shift+R)後,就能夠把樣式複製qss文件中了 QApplication a(argc, argv); setStyle(":/style/qss.qss"); #補一個實用的qss,button默認的邊框和白色背景不顯示的方法, ui->closeButton->setStyleSheet("border-style:hidden;");