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;");