首页 qt 知识点总结

qt 知识点总结

举报
开通vip

qt 知识点总结qt 知识点总结 1、QGridLayout QGridLayout包含多个grid,它并没有要求其中的每个grid的size相同,通常情况下,每个grid的size是不同的。 对于成员函数addWidget(widget, fromRow, fromColumn, rowSpan, columnSpan, alignment):rowSpan表示新添加进来的widget在垂直方向上跨越或者占据多少个grid。 columnSpan表示新添加进来的widget在水平方向上跨越或者占据多少个grid。 2、l...

qt 知识点总结
qt 知识点总结 1、QGridLayout QGridLayout包含多个grid,它并没有要求其中的每个grid的size相同,通常情况下,每个grid的size是不同的。 对于成员函数addWidget(widget, fromRow, fromColumn, rowSpan, columnSpan, alignment):rowSpan表示新添加进来的widget在垂直方向上跨越或者占据多少个grid。 columnSpan表示新添加进来的widget在水平方向上跨越或者占据多少个grid。 2、line edit的input mask 对一个line edit设置了input mask属性后,也就限定了输入字符。一般情况下,需要填写的字符位置是空白的,但是,你可以让该空白以某个字符占位,你只需在指定input mask的字符末尾添加―*?‖即可,把?,‘换为你想用来占位的一个字符。 3、利用designer 设计 领导形象设计圆作业设计ao工艺污水处理厂设计附属工程施工组织设计清扫机器人结构设计 ui 总体上来说,先创建各个控件,然后设置layout相对来说好些。另外,grid layout对设置布局前的窗口布局依赖比较大,即如果设置grid layout前的布局不同,则生效后的差别可能较大。 4、QLabel的buddy属性 在qt中,只有QLabel实现了buddy 机制 综治信访维稳工作机制反恐怖工作机制企业员工晋升机制公司员工晋升机制员工晋升机制图 。 只有你为QLabel设置了buddy后,文本中的字符?&‘才能以下划线显示(这点与其他widget不同),并创建了对应的快捷键(当然,需要+Alt),然后可以利用快捷键迅速的把光标定位到该QLabel的buddy中,例如: QLabel *what = new QLabel(―Find &What:‖); 该实例对应快捷键Alt+w。 5、QMouseEvent中的坐标 QMouseEvent中保存了两个坐标,一个是全局坐标,当然另外一个是局部坐标。 全局坐标(globalPos())即是桌面屏幕坐标(screen coordinates),这个跟windows下的调用getCursorPos函数得到的结果一致。 局部坐标(pos())即是相对当前active widget的坐标,左上角坐标为(0, 0)。 补充一个 公式 小学单位换算公式大全免费下载公式下载行测公式大全下载excel公式下载逻辑回归公式下载 : this->mapFromGlobal(this->cursor().pos()) = event.pos() 6、鼠标跟踪 在qt中,鼠标跟踪对应函数mouseMoveEvent。但是,默认情况下他并不能如期象你想象的那样响应鼠标的移动。此时,你只需在合适的位置调用一下函数setMouseTracking(true) 即可。 默认情况下,mouseMoveEvent响应你按下鼠标的某个键(拖动,但不局限于左键拖动)的鼠标移动。 7、鼠标左键拖动和左键点击的判断 鼠标左键点击很容易判断,一般就是在重写mousePressEvent函数,示例如下: void XXXWidget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt:leftButton) { // todo … } } 左键拖动的判断一般放在mouseMoveEvent函数中,但是你不能向上例一样来判断,因为该函数的event参数总是返回Qt::NoButton。你可以这样做: void XXXWidget::mouseMoveEvent(QMouseEvent *event) { if(event->buttons() & Qt:leftButton) { // todo … } } 8、窗口有一个子窗口,子窗口随着父窗口最小化而最小化的实现: child = new QWidget(parent); child->setWindowFlags(Qt::Window); 但是,如果父子窗口都显示的话,此时销毁父窗口,子窗口依然显示;然后关闭子窗口,才算完全关闭了整个窗口。理想的做法是这样的: child = new QWidget(parent); child->setWindowFlags(Qt::Window | Qt::SubWindow); 9、解决中文乱码问题 //解决中文乱码问题 QTextCodec::setCodecForTr(QTextCodec::codecForName(―GB2312″)); QTextCodec::setCodecForLocale(QTextCodec::codecForName(―GB2312″)); QTextCodec::setCodecForCStrings(QTextCodec::codecForName(―GB2312″)); 10、实现多窗体切换。 信号通讯方法(参数1事件响应对象,参数2响应事件,参数3本实例对象指针,参数 4响应方法) connect(this->ui->butSumbie, SIGNAL(clicked()), this, SIGNAL(send1())); 信号通讯方法(参数1事件响应对象,参数2响应事件,参数3本实例对象指针,本实 例对象执行方法) connect(this->ui->butSumbie, SIGNAL(clicked()), this, SLOT(close())); 事件中调用说明: 信号通讯方法(参数1事件响应对象,参数2响应事件,参数3本实例对象指针,参数 4响应方法) MyWidget w; 执行权限交给主窗体 app.setMainWidget(&w); 11、获取当前执行程序路径:QCoreApplication::applicationDirPath() 12、获取当前执行程序文件夹下全部文件内容并且保存到comboBox中。 QDir dir(QCoreApplication::applicationDirPath()); 通过QDir获取目录下全部文件与文件夹 QFileInfoList qFilelist = dir.entryInfoList(); for(int i=0;icomboBox->addItem(qFilelist.value(i).fileName(),i); } 13、文件读取实现内容实现代码。 QFile file(ui->comboBox->itemText(index)); if(file.open(QIODevice::ReadOnly))//以只读方式打开文件 { FileName = ui->comboBox->itemText(index); QTextStream ts(&file); QTextCodec *codec=QTextCodec::codecForName(―GBK‖); ts.setCodec(codec); ui->textEdit->setText(QString::null); QString line; do{ line = ts.readLine(); if(!line.isNull()) line+=‖\n‖; ui->textEdit->insertPlainText(line); } while (!line.isNull()); file.close(); } 14、文件写入实现代码段 QFile file(this->FileName); if(file.open(QIODevice::ReadWrite))//以读写方式打开文件 { QTextStream qts(&file); QTextCodec *codec=QTextCodec::codecForName(―GBK‖); qts.setCodec(codec); QString text = ui->textEdit->document()->toPlainText(); qts<setupUi(this); db = QSqlDatabase::addDatabase(―QODBC‖);//定义数据库连接类型。db对象在执行 QSqlQueryModel绑定中一直必须是开启状态并且要可见否则无数据内容显示。 db.setDatabaseName(QString(―DRIVER={SQL Server};‖ ―SERVER=%1;DATABASE=%2;UID=%3;PWD=%4″) .arg(―127.0.0.1″) .arg(―Northwind‖) .arg(―sa‖) .arg(―sa‖)); db.open(); QSqlQuery query(db);//可以执行查询与删除修改添加操作对象。 query.exec(―select top 10 * from dbo.Orders‖); if(query.numRowsAffected() == -1) { QMessageBox::about(this,‖234″,‖234″); } QSqlQueryModel *model = new QSqlQueryModel; ui->tableView->setWindowTitle(―model‖); model->setQuery(―select top 10 * from dbo.Orders‖); ui->tableView->setModel(model); ui->tableView->show(); 16、例用QTableWidget实现表格样式自定义显示结构。 QSqlDatabase db; db =QSqlDatabase::addDatabase(―QODBC‖); db.setDatabaseName(QString(―DRIVER={SQL Server};‖ ―SERVER=%1;DATABASE=%2;UID=%3;PWD=%4″) .arg(―192.168.0.16″) .arg(―Northwind‖) .arg(―sa‖) .arg(―sa‖)); db.open(); QSqlQueryModel *model=new QSqlQueryModel(this); model->setQuery(―select * from EmployeeTerritories where EmployeeID<4″); QStringList List; List.push_back(―aa‖);List.push_back(―bb‖);setColumnCount(2);//设置字段名 setHorizontalHeaderLabels(List);//命名字段 for(int i=0;irowCount();i++) { QString s; s=model->record(i).value(―EmployeeID‖).toString(); QPushButton *LineEdit1=new QPushButton(s);//绑定在表格中的控件类型 insertRow(i); setCellWidget(i,0,LineEdit1); } db.close(); 17、实现不规则窗体显示。 //自定义不规则窗体 QPalette p = palette(); QPixmap img(―a.jpg‖); //窗体掩码图定义 //QBitmap mask(―mask.png‖); p.setBrush(QPalette::Window, QBrush(img)); setPalette(p); //设置掩模图 //setMask(mask); setWindowFlags(Qt::FramelessWindowHint); resize(800, 600); //ui->setupUi(this); 18、重写鼠标控制窗体移动事件 //声明的对象 QPoint last,pos0;//鼠标移动控制对象 //重写的鼠标移动事件 void MainWindow::mouseMoveEvent(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { //QMessageBox::about(this,‖进入移动‖,‖成功进入移动事件‖); QPoint newpos = e->globalPos(); QPoint upleft = pos0 + newpos – last; move(upleft); } } //重写的鼠标按下事件 void MainWindow::mousePressEvent(QMouseEvent *e) { if(e->button()==Qt::LeftButton) { //QMessageBox::about(this,‖进入按下‖,‖成功进入按下事件‖); last = e->globalPos(); pos0 = e->globalPos() – e->pos(); } } 19、QT中调用DLL实现代码段 这个推荐一款小工具 viewdll.exe 。实例代码和工具下面提供下载。将DLL文件直接拖 过去,就直接显示DLL里的函数名。当然也不是所有DLL都能显示。 用QT生成DLL,直接导出函数的方法。 用QTcreator dll向导建立工程。把所有.H文件删除,在唯一的.CPP文件中编写你所要 导出的函数,函数模版 extern ―C‖ __declspec(dllexport) int ShowMessageBox() { char *str = ―this is Dll‖; cout< #include #include int main(int argc,char* argv[]) { QApplication app(argc,argv); struct mynode { int i; }; QLibrary lib(―mydll‖); mynode* no = (mynode*)lib.resolve(―temp‖); if(no) { QMessageBox::information(0,‖name‖,QString::number(no->i)); } else QMessageBox::information(0,‖name‖,‖no==0″); return app.exec(); } 20、QT中的网络编程与实现。QT中共提供四个与套按字相关的类,分别是: QServerSocket:TCP-based server QSocket: Buffered TCP connection QSocketDevice: Platform-independent low-level socket API QSocketNotifier: Support for socket callbacks 下面介绍使用QT进行网络编程,我们使用一个简单的C/S模式网络程序说明如何使 用QT中的套接字。同时我们用TCP和UDP两种协议实现这个程序(该程序客户端与服务 端各向对方发送一个字符口串―abc‖) 1、UDP实现 UDP是不连接协议,没有客户端与服务端的概念。 1)建立套接字相关对象 QSocketDevice *MUReceiveSocket; //套接字对象 QSocketNotifier *MSocketNotifier; //套接字监听对象 2)初始化套接字相关对象 MUReceiveSocket=new QSocketDevice(QSocketDevice::Datagram); //UDP初始化 QHostAddress MyAddress; QString FakeAddress; FakeAddress = get_eth1_ip(); //取得接口IP MyAddress.setAddress(FakeAddress); MUReceiveSocket->bind(MyAddress,Port); //绑定到指定网络接口地址(IP),指定逻辑端口 MSocketNotifier = new QSocketNotifier(MUReceiveSocket->socket(),QSocketNotifier::Read,0,‖MSocketNotifier‖); //监听MUReceiveSocket套接字 3)定义用实现响应slot virtual void OnMReceive(); void Client::OnMReceive() { int ByteCount,ReadCount; char *IncommingChar; fprintf(stderr,‖Load a piece of Message!\n‖); ByteCount=MUReceiveSocket->bytesAvailable(); IncommingChar=(char *)malloc(ByteCount+1); ReadCount=MUReceiveSocket->readBlock(IncommingChar,ByteCount); IncommingChar[ByteCount]=‖; fprintf(stderr,―%s―,IncommingChar); //打印接收的字符串 } 4)关联套接字的signal和接收slot connect(MSocketNotifier,SIGNAL(activated(int)),this,SLOT(OnMReceive())); //当MSocketNotifier检测到MUReceiveSocket活跃时调用OnMReceive 5)发送字符串 char information[20]; strcpy(information,―abc―); MUReceiveSocket->writeBlock(information,length,MyAddress,2201); TCP实现 2、 TCP的实现与UDP的实现大同小异,它是面象连接的协议。这里只介绍与UDP不同的地方。 服务端: 1)套接字对象的定义 比UDP多定义一个套接字,一个用来监听端口,一个用来通信。 QSocketDevice *ServerSocket; QSocketDevice *ClientSocket; QSocketNotifier *ClientNotifier; QSocketNotifier *ServerNotifier; 2)套接字的初始化 QHostAddress MyAddress; QString FakeAddress; FakeAddress = ―127.0.0.1″; MyAddress.setAddress(FakeAddress); UINT Port=1234; ServerSocket=new QSocketDevice(QSocketDevice::Stream); ClientSocket=new QSocketDevice(QSocketDevice::Stream); ServerSocket->bind(MyAddress,Port); ServerSocket->listen(20); //20代表所允许的最大连接数 ClienttNotifier = new QSocketNotifier(ClientSocket->socket(),QSocketNotifier::Read,0,‖ClientSocket‖); ServerNotifier = new QSocketNotifier(ServerSocket->socket(),QSocketNotifier::Read,0,‖ServerSocket‖); 3)响应连接(在定义slot中响应) 当收到客户端的连接后,响应它,并以ClientSocket接收: ServerSocket->SetSocket(ClientSocket->socket()); 4)接收信息slot与UDP一致,这里不在叙述。 客户端实现: 客户端的实现与UDP实现大同小异,不同的地方只是客户端套接字不需要bind端口, 因为连接上服 务端后TCP会保持这个连接,直到通信的结束。 操作系统:ARM-LINUX QT版本:QT-2.3.2-FOR-LINUX GUI:Qtopia 在LINUX下进行网 络编程,我们可以使用LINUX提供的统一的套接字接口。但是这种方法牵涉到太多的结构 体,比如IP地址,端口转换等,不熟练的人往 往容易犯这样那样的错误。QT中提供的 SOCKET完全使用了类的封装机制,使用户不需要接触底层的各种结构体操作。而且它采 用QT本身的signal- slot机制,使编写的程序更容易理解。 QT中共提供四个与套按字相 关的类,分别是: QServerSocket:TCP-based server QSocket: Buffered TCP connection QSocketDevice: Platform-independent low-level socket API QSocketNotifier: Support for socket callbacks 下面介绍使用QT进行网络编程,我们使用一个简单的C/S模式网络程序 说明如何使用QT中的套接字。同时我们用TCP和UDP两种协议实现这个程序(该程 序 客户端与服务端各向对方发送一个字符口串―abc‖) 1、UDP实现 UDP是不连接协议,没 有客户端与服务端的概念。 1)建立套接字相关对象 QSocketDevice *MUReceiveSocket; //套接字对象 QSocketNotifier *MSocketNotifier; //套接字监听对象 2)初始化套接字相关对 象 MUReceiveSocket=new QSocketDevice(QSocketDevice::Datagram); //UDP初始化 QHostAddress MyAddress; QString FakeAddress; FakeAddress = get_eth1_ip(); //取得接 口IP MyAddress.setAddress(FakeAddress); MUReceiveSocket->bind(MyAddress,Port); //绑定到指定网络接口地址(IP),指定逻辑端口 MSocketNotifier = new QSocketNotifier(MUReceiveSocket->socket(),QSocketNotifier::Read,0,‖MSocketNotifier‖); //监听MUReceiveSocket套接字 3)定义用实现响应slot virtual void OnMReceive(); void Client::OnMReceive() { int ByteCount,ReadCount; char *IncommingChar; fprintf(stderr,‖Load a piece of Message!\n‖); ByteCount=MUReceiveSocket->bytesAvailable(); IncommingChar=(char *)malloc(ByteCount+1); ReadCount=MUReceiveSocket->readBlock(IncommingChar,ByteCount); IncommingChar[ByteCount]=‖; fprintf(stderr,―%s―,IncommingChar); //打印接收的字符串 } 4)关联套接字的signal和接收slot connect(MSocketNotifier,SIGNAL(activated(int)),this,SLOT(OnMReceive())); //当 MSocketNotifier检测到MUReceiveSocket活跃时调用OnMReceive 5)发送字符串 char information[20]; strcpy(information,―abc―); MUReceiveSocket->writeBlock(information,length,MyAddress,2201); 2、TCP实现 TCP 的实现与UDP的实现大同小异,它是面象连接的协议。这里只介绍与UDP不同的地方。 服 务端: 1)套接字对象的定义 比UDP多定义一个套接字,一个用来监听端口,一个用来 通信。 QSocketDevice *ServerSocket; QSocketDevice *ClientSocket; QSocketNotifier *ClientNotifier; QSocketNotifier *ServerNotifier; 2)套接字的初始化 QHostAddress MyAddress; QString FakeAddress; FakeAddress = ―127.0.0.1″; MyAddress.setAddress(FakeAddress); UINT Port=1234; ServerSocket=new QSocketDevice(QSocketDevice::Stream); ClientSocket=new QSocketDevice(QSocketDevice::Stream); ServerSocket->bind(MyAddress,Port); ServerSocket->listen(20); //20代表所允许的最大连接数 ClienttNotifier = new QSocketNotifier(ClientSocket->socket(),QSocketNotifier::Read,0,‖ClientSocket‖); ServerNotifier = new QSocketNotifier(ServerSocket->socket(),QSocketNotifier::Read,0,‖ServerSocket‖); 3)响 应连接(在定义slot中响应) 当收到客户端的连接后,响应它,并以ClientSocket接收: ServerSocket->SetSocket(ClientSocket->socket()); 4)接收信息slot与UDP一致,这里不 在叙述。 客户端实现: 客户端的实现与UDP实现大同小异,不同的地方只是客户端套接 字不需要bind端口,因为连接上服 务端后TCP会保持这个连接,直到通信的结束。 21、Qt窗体布局操作 布局中主要的操作有 水平布局, 垂直布局, 打破布局。 当只有一个控件时,不能进行布局操作。布局操作是多个控件,或者对话框的操纵。 选择多个窗体控件,按住shift键,鼠标点击选取,右键进行布局操纵。 当选中对话框主窗体时,可以进行窗体上控件的布局操作。 该操纵将对窗体上的控件或者布局进行,水平布局或者垂直布局操纵 22、Qt绘图模式 Qt助手,放大缩小,很方便。 绘图系统 主要基于三个类,QPainter, QPaintDevice, QPaintEngine. QPainter用于执行绘图操作。QPaintDevice使用QPaint进行绘图所使用的二维空间。 QPaintEngine提供了在不同设备上的 绘图接口,被QPainter, QPaintDevice内部使用,对 于程序员来说是隐藏的,只有在创建自己的设备类型时,才能用到。 QPainter能用画笔作图,画文字或者图形。 画 填充 创建设备 读写图形文件 样式 QPaintDevice是用于画图的设备的基类。 QPaintDevice的子类有 QWidget, QImage, QPixmap, QGLWidget, QGLPixelBuffer, QPicture and QPrinter。 23、CListWidget与CTableWidget编程注意事项 在执行CListWidget与CTableWidget等类似的列表控件的Clear操作时,系统经常崩溃, 原因分析。这个clear操作因为改变了列表的内容,会触发其它的信号。特别是下面的两个 函数。 CListWidget的函数 void currentItemChanged ( QListWidgetItem * current, QListWidgetItem * previous ) void currentRowChanged ( int currentRow ) CTableWidget的函数。 void currentCellChanged ( int currentRow, int currentColumn, int previousRow, int previousColumn ) void currentItemChanged ( QTableWidgetItem * current, QTableWidgetItem * previous ) 如果,在下面的函数中,没有加入信号参数检测,就很容易出错。主要检查currentRow 是否大于或者等于0。current,previous 是否有效。如果不检查,并根据该参数,调用了其它的方法。当currentRow =-1; 时,就会发生错误。 ui.tableWidget->item(row, 0); row=-1时,调用就会产生错误。 ui.listWidget->item(row); row=-1时,调用就会产生错误。 错误解决方法:加入错误检查, if (row>=0){//其它相关处理} 24、一个工程中出现多个QMainWindow并同时显示的 方案 气瓶 现场处置方案 .pdf气瓶 现场处置方案 .doc见习基地管理方案.doc关于群访事件的化解方案建筑工地扬尘治理专项方案下载 。 问题描述: 在一个CMainWindow CMyWin1的继承类中,如果再使用一个CMainWindow类CMyWin2; 在CMyWin1中使用以下代码、 CMyWin2 mw; mw.show () mw 一闪就没有了。具体原因不明。 定义窗体局部变量: CDataManager *m_pDataMager; 调用过程如下,并建立信号连接,监控信号 destryed,接收道该信号时,做一个槽处理。 if (m_pDataMager) { m_pDataMager->setVisible (true); m_pDataMager->showNormal (); //m_pDataMager-> } else { m_pDataMager = new CDataManager(); connect(m_pDataMager, SIGNAL(destroyed(QObject*)), this, SLOT(after_DataManage_Destoryed(QObject*))); m_pDataMager->setVisible (true); } 在函数after_DataManage_Destoryed中,进行窗体的delete,并设置变量为NULL。 void SeismicRecogn::after_DataManage_Destoryed(QObject *obj) { //QMessageBox::information(this,‖Test Box‖,‖DataManage_Destoryed!‖); if (m_pDataMager) { disconnect(m_pDataMager, SIGNAL(destroyed(QObject*)), this, SLOT(after_DataManage_Destoryed(QObject*))); obj->deleteLater(); m_pDataMager =NULL; } } 25、资源文件的动态加载 在构造函数中添加如下: QIcon icon; icon.addPixmap(QPixmap(QString::fromUtf8(―../resource/well.png‖)), QIcon::Normal,QIcon::Off); ui.actionLoad->setIcon(icon); tableWidget设置高度宽带 ui.tableWidget->setColumnWidth(0,280); ui.tableWidget->setColumnWidth(1,280); for (int i=0;i<10;i++) ui.tableWidget->setRowHeight(i,20); 26、如何对LineEdit输入数据进行格式限制。 QLineEdit 中对输入字符输入格式的控制通过inputMask与validators实现。 使用时,详细阅读2个的说明。 QIntValidator *vv=new QIntValidator(this); ui.lineEdit->setValidator (vv); 27、二维图形框架Graphics View Graphics View框架实现了模型,视图结构的图形管理,能对大量的图元进行管理,支持碰撞检测、坐标变换和图元组等多种方便的操作。Graphics View支持事件传播体系结构,可以使图元在场景(scene)中得到提高了一倍的精确交互能力。图元能够处理键盘事件,鼠标按下、移动、释放和双击事 件,也能跟踪鼠标的移动。在Graphics View框架中,通过BSP(二元空间划分树,Binary Space Partionng)来提供快速的图元查找,这样就能实时地显示大场景,甚至上百万个图元。 Graphics View框架提供基于图元的模型,视图编程,类似于Qt InterView的模型,视图结构,只是这里的数据是图形。Graphics View框架中包括三个主要的类:QGraphicsItem, QGraphicsScene 和 QGraphicsView。 Graphics View为大量定制的2维图元的管理与交互提供了一个框架,可以实现这些图元的 可视化,并支持缩放和旋转。 28、Graphics View框架继续学习 主要内容:场景 QGraphicsScene 视图 QGraphicsView 图元 QGraphicsItem 示例:Examples and Demos >> Graphics View QGraphicsScene是QGraphicsItems的容器。它与QGraphicsView一起实现了图元的可视 化,例如线,矩形,文本,以及定制的图元。QGraphicsScene也提供了以下功能,让你高 效的确定图元的位置以及图元的可视性。 QGraphicsScene scene; scene.addText(―Hello, world!‖); QGraphicsView view(&scene); view.show(); 重点示例程序: Diagram Scene //图元的外接矩形区域(虚函数的实现) QRectF CGeoObjCnoline::boundingRect() const //图元的绘制路径(虚函数的实现) QPainterPath CGeoObjCnoline::shape() const //图元的绘制(虚函数的实现) void CGeoObjCnoline::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) 29、要想界面一直存在用new创建 用new指针生成,起作用 private: Ui::cdtestClass ui; QGraphicsScene *scene; QGraphicsView *view; cdtest::cdtest(QWidget *parent, Qt::WFlags flags): QMainWindow(parent, flags) { ui.setupUi(this); scene = new QGraphicsScene(); scene->setSceneRect (-400,-300,800,600); scene->setItemIndexMethod (QGraphicsScene::NoIndex ); scene->addText (―Good‖); view = new QGraphicsView(scene); ui.layTest->addWidget(view); view->update(); } 用局部变量不起作用 void cdtest::on_actionTest_triggered() { QGraphicsScene scene; scene.setSceneRect (-400,-300,800,600); scene.setItemIndexMethod (QGraphicsScene::NoIndex ); scene.addText (―Good‖); QGraphicsView view(&scene); ui.layTest->addWidget(&view); view.update(); } 指针用局部变量,使用的时候new,起作用。 void cdtest::on_actionTest_triggered() { QGraphicsScene *scene; scene = new QGraphicsScene; scene->setSceneRect (-400,-300,800,600); scene->setItemIndexMethod (QGraphicsScene::NoIndex ); scene->addText (―Good‖); QGraphicsView *view; view =new QGraphicsView(scene); ui.layTest->addWidget(view); view->update(); } 30、QTableView根据内容自动调整列宽行高 1: 使用QTableView自己带的函数,函数原型如下: ui.tableWidget->resizeColumnToContents (0); 将第一列根据内容自动调整列宽。 根据内容自动调整某列的列宽 void QTableView::resizeColumnToContents ( int column ) [slot] Resizes the given column based on the size hints of the delegate used to render each item in the column. 根据内容自动调整所有列的列宽 void QTableView::resizeColumnsToContents () [slot] Resizes all columns based on the size hints of the delegate used to render each item in the columns. 根据内容自动调整某一行的行高 void QTableView::resizeRowToContents ( int row ) [slot] Resizes the given row based on the size hints of the delegate used to render each item in the row. 根据内容自动调整所有行的行高。 void QTableView::resizeRowsToContents () [slot] Resizes all rows based on the size hints of the delegate used to render each item in the rows. 31、QGraphicsItem中的碰撞检测描述 QGraphicsItem是图元基类。QGraphics View框架提供了几种 标准 excel标准偏差excel标准偏差函数exl标准差函数国标检验抽样标准表免费下载红头文件格式标准下载 的图元,如矩形(QGraphicsRectItem、椭圆(QGraphicsEllipseItem)和文本图元 (QGraphicsTextItem)等。用户可以继承QgraphicItem实现符合自己需要的图元。 QGraphicsItem具有以下功能: 处理鼠标按下、移动、释放、双击、悬停、滚轮和右键菜单事件 处理键盘输入事件 处理拖放事件 分组 碰撞检测 图元有自己的坐标系统,也提供场景和图元、图元与图元之间的坐标转换函数。图元可以包含子图元。 要创建自己的图元,必须首先创建QGrahicsItem的一个子类,然后开始实现他的2个纯虚函数。一个是boundingRect(),用于返回图元绘制所需要的估测区域。另一个是paint,它实现实际的绘图操纵。举例: class SimpleItem : public QGraphicsItem { public: QRectF boundingRect() const { qreal penWidth = 1; return QRectF(-10 – penWidth / 2, -10 – penWidth / 2, 20 + penWidth / 2, 20 + penWidth / 2); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget) { painter->drawRoundedRect(-10, -10, 20, 20, 5, 5); } }; boundingRect函数有几个目的。QGraphicsScene的图元索引就是建立在boundingRect的基础上。 QGraphicsView也使用这个函数来从视图上将不可见的图元移去,以及在绘制重叠的图元时决定需要重新组织的区域。另 外,QGraphicsItem的碰撞检测机制(collision detection)使用boundingRest来提高高效的处理。更好的碰撞检测算法是基于shape函数的调用,shape函数将图元的形状的准确 外观以QPainterPath返回。 QGraphicsScene认为所有图元的boundingRect函数与shape函数都是不发生改变的,除非用户进行通知。如果你想改变一个图元的范围,必需先调用prepareGeometryChange 以允许QGraphicsScene进行更新。 碰撞检测可以通过以下两种方式实现: 重新实现shape函数返回一个准确的图元外观形状,依赖collidesWithItem函数进行缺省的 碰撞检测,如果形状非常的复杂,该检测将是非常耗时的。 重新实现collidesWithItem函数,为自己的定制图元编写碰撞检测算法。 对于多点成线的图元可以使用下面的方式返回shape。 QPainterPath path; //直线的绘制路径 if (m_pointList.count()>0) { int iSize; iSize = m_pointList.size(); path.moveTo (m_pointList[0]); for(int i=1;i=1;i–) { path.lineTo (m_pointList[i*2-1]); } path.closeSubpath(); } return path; 32、sql中二进制文件通过QByteArray读写 从数据库到文件 QSqlQuery myquery( *pDatabase); QByteArray myba; if(myquery.exec(sql)) { QSqlRecord myrecord = myquery.record(); if (myquery.next()) { myba = myquery.value(myrecord.indexOf(―Settings‖)).toByteArray();//读取二进制对 象 } } else { initBoundary(); return false; } QFile mybfile(MapDataFilename); if (!mybfile.open(QIODevice::WriteOnly)) { initBoundary(); return false; } mybfile.write (myba); mybfile.close(); 从文件到数据库 //将文件存入数据库 QByteArray mapData; QFile file(MapDataFilename); if (!file.open(QIODevice::ReadOnly)) return false; mapData = file.readAll(); file.close(); QSqlDatabase* pDatabase = CAccessController::getInstance()->getAccesser(g_dbXMLFilePath); if (pDatabase ==0 ) { // QMessageBox::information(this, ―Error‖, CAccessController::getInstance()->lastError()); return false; } QSqlQuery query( *pDatabase); query.prepare(―update p_project SET Settings = :set where ID_P = :idp‖); query.bindValue (―:set‖,mapData); query.bindValue (―:idp‖,CMainConfig::CurProjectID); bool bRtn = query.exec(); if (!bRtn) { QSqlError er =query.lastError (); QString ss= er.text(); return false; } 33、QGraphicsView放大缩小中心属性分析 将下面的函数注释掉,是resize,不发生缩放。 void CBaseMapForm::resizeEvent ( QResizeEvent * event ) { //m_view->doZoomAll(); } QMatrix可以直接进行文件存储。 << >>。 34、帮助文件的调用执行问题 帮助文件安装制作: 取得当前可执行程序的路径 QString strUrl=QApplication::applicationDirPath () ; strUrl=QString(―file:///%1/help.htm‖).arg (strUrl) 用客户机的浏览器,打开网页 desktopServices.openUrl(qqq); 35、最简单的图形显示控件QLabel imageLabel = new QLabel; imageLabel->setWordWrap(true); imageLabel->setAlignment(Qt::AlignCenter); imageLabel->setPixmap(QPixmap(―:/images/image.png‖)); QPixmap的伸缩 ui.lblImage->setPixmap(pixmap.scaled(ui.lblImage->size()-QSize(40,40),Qt::KeepAspe ctRatio, Qt::FastTransformation)); 36、取得QTableView的特定行,特定列的数据 QModelIndex index = ui.tableView->currentIndex(); if (!index.isValid()) { QMessageBox::information (NULL,‖提示‖,‖请先选择一行数据。‖); return; } int iRow; iRow = index.row(); QAbstractItemModel* model = ui.tableView->model(); //取得层数据库的数据表名 index = model->index(iRow,1,QModelIndex()); QString strHorizonName; strHorizonName = index.data().toString(); 37、qt下获得屏幕的分辨率 在Qt中提供了QDesktopWidget类,提供屏幕的有关信息. 可以这么作: QDesktopWidget *d=QApplication::desktop(); int width=d->widht(); //屏幕的宽度 int height=d->height(); //屏幕的高度 或者简写如下: int width=QApplication::desktop()->width(); int height=QApplication::desktop()->height(); 38、干掉QT窗体的标题栏。。 setWindowFlags(Qt::FramelessWindowHint); 39、设置QT按钮为透明。 //就是这句能够实现透明,真是意外的发现,希望对一些学习的朋友有点帮助 ui->pushButton->setFlat(true); 40、设置QT窗体置顶。 this->setWindowFlags(Qt::WindowStaysOnTopHint); 41、判断sqlite数据表是否存在。 QStringList existTables; existTables=dataBase->tables(); if(!existTables.contains(userId)) QSqlDatabase db = QSqlDatabase::addDatabase(―QSQLITE‖); //创建不带名称的数据库连接,可以理解成ADO中的Connection Driver Class name Constructor arguments File to include QPSQL QPSQLDriver PGconn *connection qsql_psql.cpp QMYSQL QMYSQLDriver MYSQL *connection qsql_mysql.cpp QOCI QOCIDriver OCIEnv *environment, OCISvcCtx *serviceContext qsql_oci.cpp QODBC QODBCDriver SQLHANDLE environment, SQLHANDLE qsql_odbc.cpp connection QDB2 QDB2 SQLHANDLE environment, SQLHANDLE connection qsql_db2.cpp QTDS QTDSDriver LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName qsql_tds.cpp QSQLITE QSQLiteDriver sqlite *connection qsql_sqlite.cpp QIBASE QIBaseDriver isc_db_handle connection qsql_ibase.cpp ODBC连接适合数据库类型 连接方式access ―Driver={microsoft access driver(*.mdb)};dbq=*.mdb;uid=admin;pwd=pass;‖dBase ―Driver={microsoft dbase driver(*.dbf)};driverid=277;dbq=————;‖oracle ―Driver={microsoft odbc for oracle};server=oraclesever.world;uid=admin;pwd=pass;‖MSSQL server ―Driver={sql server};server=servername;database=dbname;uid=sa;pwd=pass;‖MS text ―Driver={microsoft text driver(*.txt; *.csv)};dbq=—–;extensions=asc,csv,tab,txt;Persist SecurityInfo=false;‖Visual Foxpro ―Driver={microsoft Visual Foxpro driver};sourcetype=DBC;sourceDB=*.dbc;Exclusive=No;‖MySQL ―Driver={mysql};databa se=yourdatabase;uid=username;pwd=yourpassword;option=16386;‖SQLite ―Driver={SQ Lite3 ODBC Driver};Database=D:\SQLite\*.db‖PostgreSQL ―Driver={PostgreSQL ANSI};server=127.0.0.1;uid=admin;pwd=pass;database=databaseName‖OLEDB连接适 合的数据库类型 连接方式access ―Provider=microsoft.jet.oledb.4.0;data source=your_database_path;user id=admin;password=pass;‖oracle ―Provider=OraOLEDB.Oracle;data source=dbname;user id=admin;password=pass;‖MS SQL Server ―Provider=SQLOLEDB;data source=machinename;initial catalog=dbname;userid=sa;password=pass;‖MS text ―Provider=microsof.jet.oledb.4.0;data source=your_path;Extended Properties‘text;FMT=Delimited‘ //参见QSqlDatabase的文档 #addDatabase db.setDatabaseName(―UserDB‖); if ( !db.open()) { QMessageBox::critical(NULL, QObject::tr(―Collection‖), QObject::tr(―数据库连接失败~‖)); return ; } if(db.tables().isEmpty()) { QMessageBox::critical(NULL, QObject::tr(―Collection‖), QObject::tr(―数据库连接失败~‖)); } 42、QString 转换 unsigned char* 。 QString str = ―ABCD‖; int length = str.length(); unsigned char *sequence = NULL; sequence = (unsigned char*)qstrdup(str.toAscii().constData()); 43、怎样获取手机串号, TPlpVariantMachineId machineId; PlpVariant::GetMachineIdL(machineId); 44、自定义按键事件与控件大小变化事件 //按键事件 virtual void keyPressEvent(QKeyEvent *k); //控件改变重绘事件 virtual void paintEvent(QPaintEvent *); 45、获取QTableView行信息内容 QSqlQueryModel model;//以绑定数据内容的QSqlQueryModel query.prepare(―delete from glossary where [work]=:work and [explain]=:explain‖); QModelIndex index = ui->tableView->currentIndex(); query.bindValue(―:work‖, model->record(index.row()).value(0).toString()); query.bindValue(―:explain‖, model->record(index.row()).value(1).toString()); 由于本按键精灵在direct X游戏上按键存在问题,因为direct并不是读取系统函数sendmessage 或者post message函数的。而是直接读取硬件层的。所以会在部分游戏无法使用按键。很多玩家要求我修改这个缺陷。但是很遗憾我也没那么多时间去写个键盘驱动。 软件其实算是半成品,其实我想做好它的,可是有人心而力不足啊。没太多时间去搞那么多软件。。所以喜欢按键精灵的朋友可以参考我的实现方式。不过是 QT+WIN SDK实现。我很讨厌MFC那种机理。不就是用宏封装了SDK吗。要搞的那么复杂嘛。乱成一套。还不如直接用win32API开发简单些。还不如用 VCL。虽然我用VCL用了一年却发现拓展性太差了。面向对象也差的一逼啊。自定义控件这么麻烦。喜欢QT的朋友加我们QT社区群吧:3855916 按我一贯的原则。我只公开一部分源码。我非常讨厌别人拿我的代码一改就成自己的了。我只提供一个技术参考。作为一名编程爱好者。虽然不算职业,当我比公司里那些菜鸟强多了吧。。也提供很多我开发软件源码了。 下面的英文写的不好。因为我的学历太低了。初中都没毕业哎。。可怜我。。所以看不懂变量和函数你慢慢琢磨。相信你会懂的 MainWindow.cpp [cpp] view plaincopy 1. #include "mainwindow.h" 2. #include "ui_mainwindow.h" 3. 4. MainWindow::MainWindow(QWidget *parent) : 5. QMainWindow(parent), 6. ui(new Ui::MainWindow),runLoop(false) 7. { 8. ui->setupUi(this); 9. this->setFixedSize(this->width(),this->height());//设置窗口 指定大小 10. 11. showScript=new ShowScript(this); 12. shutdown=new ShutdownTask(this); 13. 14. connect(ui->saveScriptButton,SIGNAL(clicked()),showScript,S LOT(SaveScript())); 15. connect(ui->addScriptButton,SIGNAL(clicked()),showScript,SI GNAL(AddScript())); 16. 17. connect(ui->singleRadioButton,SIGNAL(clicked(bool)),showScr ipt,SIGNAL(SetSingleList(bool))); 18. connect(ui->loopRadioButton,SIGNAL(clicked(bool)),showScrip t,SIGNAL(SetLoopList(bool))); 19. 20. connect(qApp,SIGNAL(aboutToQuit()),showScript,SLOT(HintSave NewScript())); 21. 22. connect(ui->editCheckBox,SIGNAL(clicked(bool)),showScript,S LOT(SetEditShowMode(bool))); 23. 24. connect(showScript,SIGNAL(SetCheckBox(bool)),ui->editCheckB ox,SLOT(setChecked(bool))); 25. connect(showScript,SIGNAL(ChangeLoop(bool)),SLOT(ChangeLoop (bool))); 26. 27. connect(shutdown,SIGNAL(Error(QString)),showScript,SLOT(Err or(QString))); 28. 29. connect(ui->addHotKeyPushButton,SIGNAL(clicked()),showScrip t,SLOT(ShowHotKeyDialog())); 30. 31. 32. ui->shutdownTypeComboBox->addItems(QStringList()<timeEdit->setVisible(false); 34. ui->shutdownTypeComboBox->setVisible(false); 35. ui->affirmPushButton->setVisible(false); 36.} 37. 38.MainWindow::~MainWindow() 39.{ 40. delete ui; 41.} 42. 43.void MainWindow::on_shutdownTypeComboBox_currentIndexChanged(in t index) 44.{ 45. ui->timeEdit->setVisible(index); 46. 47.} 48. 49.void MainWindow::on_affirmPushButton_clicked(bool checked) 50.{ 51. ui->shutdownTypeComboBox->setEnabled(false); 52. ui->timeEdit->setEnabled(false); 53. 54. if(!ui->shutdownTypeComboBox->currentIndex()) 55. { 56. connect(showScript,SIGNAL(ScriptListFinish()),SLOT(Scr iptListFinish())); 57. 58. }else 59. { 60. shutdown->SetCountDown(ui->timeEdit->time()); 61. connect(shutdown,SIGNAL(ShowCountTime(QTime)),SLOT(Show CountTime(QTime))); 62. } 63. 64.} 65. 66. 67.void MainWindow::on_shutdownCheckBox_clicked(bool checked) 68.{ ui->shutdownTypeComboBox->setVisible(checked); 69. 70. ui->affirmPushButton->setVisible(checked); ui->shutdownTypeComboBox->setEnabled(true); 71. 72. ui->timeEdit->setEnabled(true); 73. 74. if(!checked) 75. { 76. ui->timeEdit->setVisible(checked); 77. disconnect(showScript,SIGNAL(ScriptListFinish()),this, SLOT(ScriptListFinish())); 78. disconnect(shutdown,SIGNAL(ShowCountTime(QTime)),this, SLOT(ShowCountTime(QTime))); 79. shutdown->StopCountDown(); 80. } 81. 82. this->ChangeLoop(runLoop); 83.} 84. 85.void MainWindow::ChangeLoop(const bool &loop) 86.{ 87. runLoop=loop; 88. if(ui->shutdownCheckBox->checkState()) 89. { 90. ui->shutdownTypeComboBox->setCurrentIndex(runLoop); 91. ui->shutdownTypeComboBox->setVisible(!runLoop); 92. ui->timeEdit->setVisible(runLoop); 93. } 94.} 95. 96.void MainWindow::ScriptListFinish() 97.{ 98. shutdown->Shutdown(); 99.} 100. 101. void MainWindow::ShowCountTime(const QTime &countTime)//显 示倒计时时间 { 102. 103. ui->timeEdit->setTime(countTime); 104. } 105. 106. void MainWindow::on_accessPushButton_clicked() 107. 108. { 109. desktopServices.openUrl(QUrl(" 访问开发者空间 .com"));// 110. } 111. 112. void MainWindow::on_aboutPushButton_clicked() 113. { 114. QMessageBox::about(this,tr("About"),tr("This is Softwa re Developer:Jason's.Alex, QQ:531401335, Access WebSite Get More Software:bctalk.5d6d.com," 115. "ΛV Software(2009-2011), F12Record/StopRecord Script ..Shift +F12Run/StopRun Script")); 116. } 下面就是记录按键的实现。recordScript.cpp [cpp] view plaincopy 1. #include "recordScript.h" 2. #include 3. 4. RecordScript *recordScript; 5. 6. 7. QStringList RecordScript::functionKey=QStringList()<<"F1"<<"F2" <<"F3"<<"F4"<<"F5"<<"F6"<<"F7"<<"F8"<<"F9"<<"F10"<<"F11"<<"F12" ; 8. 9. QStringList RecordScript::numKey=QStringList()<<"0"<<"1"<<"2"<< "3"<<"4"<<"5"<<"6"<<"7"<<"8"<<"9"; 10. 11.QStringList RecordScript::letterKey=QStringList()<<"A"<<"B"<<"C "<<"D"<<"E"<<"F"<<"G"<<"H"<<"I"<<"J"<<"K"<<"L"<<"M"<<"N"<<"O"<< "P"<<"Q"<<"R"<<"S"<<"T" <<"U"<<"V"<<"W"<<"X"<<"Y"<<"Z"; 12. 13. 14. 15.RecordScript::RecordScript():dll("Hook.dll"),count(0),delay(0), record(false),run(false) { 16. 17. 18. SetupMouseEvent=(SETUPMOUSEEVENT)dll.resolve("SetupMouseEve nt"); 19. SetupKeyEvent=(SETUPKEYEVENT)dll.resolve("SetupKeyBoardEven t"); 20. 21. if(!SetupMouseEvent) 22. emit Error(tr("SetupMouseEvent Failed!")); 23. if(!SetupKeyEvent) 24. emit Error(tr("SetupKeyBoardEvent Failed!")); 25. 26. 27. if(!SetupMouseEvent(SendMouseEvent)) 28. emit Error(tr("SetupMouseEvent Bad!")); 29. 30. if(!SetupKeyEvent(SendKeyEvent)) 31. emit Error(tr("SetupKeyEvent Bad!")); 32. 33. connect(&timer,SIGNAL(timeout()),SLOT(IntervalCount())); 34. timer.start(1); 35.} 36. 37. 38.RecordScript::~RecordScript() 39.{ 40. dll.unload(); 41.} 42. 43. 44.void RecordScript::MouseScript(const int keyType,const int x,co nst int y) //分析鼠标脚本 45. { 46. 47. QString click="Mouse:"; 48. switch(keyType) 49. { 50. case 0: 51. click+="LeftClick"; 52. 53. break; 54. 55. case 1: 56. click+="RightClick"; break; 57. 58. 59. case 2: click+="Move"; 60. 61. } 62. 63. 64. if(record) 65. emit KeyEvent(click+"("+QString::number(x)+"*"+QString: :number(y)+")"+",Time:"+QString::number(GetDelay())+";"); 66. } 67. 68.void RecordScript::KeyScript(const int hotKey,const int key)// 分析键盘脚本 69.{ 70. QString systemKey,commonKey,tempKey="Key:"; 71. switch(hotKey) 72. { 73. case 1: 74. systemKey="Shift+"; 75. break; 76. 77. case 2: 78. systemKey="Ctrl+"; 79. break; 80. case 3: 81. systemKey="Alt+"; 82. break; 83. } 84. 85. switch(key) 86. { 87. case 0x00000009: 88. commonKey="Tab"; 89. break; 90. 91. case 0x00000008: 92. commonKey="BackSpace"; 93. break; 94. 95. case 0x0000000D: 96. commonKey="Enter"; 97. break; 98. case 0x000000014: 99. 100. 101. commonKey="CapsLock"; break; 102. 103. case 0x20: 104. 105. commonKey="Space"; 106. break; 107. 108. case 0x1b: 109. commonKey="Esc"; 110. break; 111. 112. } 113. 114. 115. if(key>=0x30 && key<=0x39) //数字键0-9 116. commonKey=numKey[key-0x30]; 117. 118. else if(key>=0x41 && key<=0x5a)//字母a-z 119. commonKey=letterKey[key-0x41]; 120. 121. else if (key>=0x70 && key<=0x7b)//F1-F12; 122. commonKey=functionKey[key-0x70]; 123. 124. systemKey+=commonKey; 125. 126. if(systemKey=="F12") 127. { 128. record=!record; 129. if(record&&!run) 130. emit StartRecord();//开始录制脚本 131. else 132. emit StopRecord();//停止录制脚本 133. 134. return; 135. } 136. 137. if(systemKey=="Shift+F12")//执行脚本 { 138. 139. run=!run; 140. if(!record&&run) 141. { 142. emit StartRun(); }else 143. 144. { 145. emit StopRun(); } 146. 147. } 148. 149. 150. if(!commonKey.isEmpty() && record)//判断是否按下普通键 和是否启用记录,否则不予发送信号 151. emit KeyEvent(tempKey+systemKey+","+"Time:"+QStrin g::number(GetDelay())+";"); 152. 153. } 154. 155. void RecordScript::IntervalCount(void) 156. { 157. count++; 158. } 159. 160. int RecordScript::GetDelay(void)//获取延迟时间 161. { 162. if(delay==0) 163. { 164. delay=count; 165. return 0; 166. } 167. int temp=count-delay; 168. delay=count; 169. 170. return temp; 171. } 172. 173. 174. 175. void SendMouseEvent(const int keyType,const int x,const in t y) 176. { 177. recordScript->MouseScript(keyType,x,y); 178. } 179. 180. void SendKeyEvent(const int hotKey,const int key) 181. { 182. recordScript->KeyScript(hotKey,key); 183. } 运行脚本的实现runscript.cpp [cpp] view plaincopy 1. #include "runscript.h" 2. 3. 4. RunScript::RunScript(QWidget *parent,const QStringList &list) : 5. QWidget(parent),scriptList(list),row(-1),loopList(false),an alysisScript(NULL) 6. { 7. tableView=new QTableView(parent); 8. tableView->setGeometry(10,60,256,600); 9. 10. 11. standardItemModel=new QStandardItemModel(this); 12. 13. 14. standardItemModel->setHorizontalHeaderLabels(QStringLis t()<setModel(standardItemModel); 16. standardItemModel->setColumnCount(2); 17. tableView->setColumnWidth(1,200); 18. tableView->setSelectionBehavior(QAbstractItemView::Sele ctRows); 19. tableView->setStyleSheet("background:rgb(189,235,238)") ; 20. tableView->setShowGrid(false); 21. tableView->setEditTriggers(QAbstractItemView::NoEditTri ggers); 22. 23. 24. deleteAction=new QAction(tr("Delete"),this); 25. connect(deleteAction,SIGNAL(triggered()),SLOT(DeleteScr ipt())); 26. 27. 28. tableView->addAction(deleteAction); 29. tableView->setContextMenuPolicy(Qt::ActionsContextMenu) ; 30. 31. 32. connect(tableView,SIGNAL(doubleClicked(QModelIndex)),SL OT(MouseDoubleClick(QModelIndex))); 33.} 34. 35. 36.void RunScript::DeleteScript()//删除脚本 37.{ 38. standardItemModel->takeRow(tableView->currentIndex().row()) ; 39.} 40. 41. 42.void RunScript::AddScript(void)//添加脚本 43. { 44. QStringList paths=QFileDialog::getOpenFileNames(this,tr("O pen File"),"/home/script/",tr("Text files(*.txt)")); 45. if(paths.isEmpty()) 46. { 47. return; 48. } 49. QString dirName; 50. 51. 52. for(QStringList::ConstIterator begin=paths.begin();begin!=p aths.end();++begin) 53. { 54. dirName=QDir(*begin).dirName(); 55. 56. 57. if(!standardItemModel->findItems(dirName).isEmpty()) 58. { 59. emit Error(tr("Script File Already:%1").arg(dirNam e)); 60. return ; 61. } 62. 63. int row=standardItemModel->rowCount(); 64. 65. QStandardItem *name=new QStandardItem(dirName); 66. QStandardItem *path=new QStandardItem(*begin); 67. 68. QLinearGradient linearGrad1(QPointF(0,0),QPointF(50,50)69. ); 70. QLinearGradient linearGard2(QPointF(0,0),QPointF(80,120 )); 71. 72. 73. linearGrad1.setColorAt(0,Qt::cyan); 74. linearGrad1.setColorAt(1,Qt::yellow); 75. 76. 77. linearGard2.setColorAt(0,Qt::yellow); 78. linearGard2.setColorAt(1,Qt::cyan); 79. 80. 81. QBrush brush1(linearGrad1),brush2(linearGard2); 82. name->setBackground(brush1); 83. path->setBackground(brush2); 84. 85. 86. standardItemModel->setItem(row,0,name); 87. standardItemModel->setItem(row,1,path); 88. standardItemModel->setVerticalHeaderItem(row-1,NULL); 89. } 90.} 91. 92. 93. 94. 95.void RunScript::MouseDoubleClick(QModelIndex index) //鼠标双击 事件 96.{ 97. row=index.row(); 98. QStandardItem *item=standardItemModel->item(row,1); 99. emit ReadScript(item->text()); 100. } 101. 102. 103. void RunScript::NextRow(void)//选择下一行 104. { if(analysisScript!=NULL) 105. 106. { 107. delete analysisScript; 108. analysisScript=NULL; 109. } 110. 111. 112. row++; if(rowrowCount()) 113. 114. { tableView->selectRow(row); 115. 116. MouseDoubleClick(tableView->currentIndex()); 117. 118. 119. StartRun(); 120. 121. 122. } 123. else if(loopList) 124. { 125. row=-1; 126. NextRow(); 127. }else 128. { 129. row=-1; 130. emit StopRun();//当脚本执行完毕后暂停脚本发送脚本 暂停信号 131. } 132. } 133. 134. 135. void RunScript::SetLoopList(bool state)//设置列表循环属 性 136. { 137. loopList=state; 138. emit ChangeLoop(loopList); 139. } 140. 141. 142. void RunScript::SetSingleList(bool state)//设置列表单循 环 143. { 144. loopList=!state; emit ChangeLoop(loopList); 145. 146. } 147. 148. 149. 150. 151. void RunScript::StartRun(void)//运行脚本 152. { QString script; 153. 154. 155. 156. for(QStringList::ConstIterator begin=scriptList.begi n();begin!=scriptList.end();++begin) 157. script+=*begin; 158. 159. 160. 161. 162. analysisScript=new AnalysisScript(script); 163. connect(analysisScript,SIGNAL(ScriptFinish()),SLOT(N extRow())); 164. connect(this,SIGNAL(StopExecuteScript()),analysisScr ipt,SLOT(StopExecute())); 165. } 显示脚本的实现:。showScript.cpp [cpp] view plaincopy 1. #include "showscript.h" 2. 3. ShowScript::ShowScript(QWidget *parent) : 4. QWidget(parent),editMode(false),newlyScript(false) 5. { 6. listView=new QListView(parent); 7. listView->setGeometry(1020,60,291,600); 8. listView->verticalScrollBar()->setStyleSheet("background:#1 235ff"); 9. 10. statusBar=new QStatusBar(parent); 11. statusBar->setStyleSheet("background:rgb(240,209,157)"); 12. 13. statusBar->setGeometry(0,parent->height()-25,parent->width( ),25); 14. standardItemModel=new QStandardItemModel(this); 15. 16. 17. runScript=new RunScript(parent,bufferScript); 18. connect(this,SIGNAL(AddScript()),runScript,SLOT(AddScript() )); 19. 20. connect(runScript,SIGNAL(Error(QString)),SLOT(Error(QString ))); connect(runScript,SIGNAL(ReadScript(QString)),SLOT(ReadScri21. pt(QString))); 22. 23. connect(this,SIGNAL(SetLoopList(bool)),runScript,SLOT(SetLo opList(bool))); 24. connect(this,SIGNAL(SetSingleList(bool)),runScript,SLOT(Set SingleList(bool))); 25. connect(runScript,SIGNAL(ChangeLoop(bool)),SIGNAL(ChangeLoo p(bool))); 26. connect(runScript,SIGNAL(StopRun()),SIGNAL(ScriptListFinish ())); 27. 28. 29. recordScript=new RecordScript; 30. connect(recordScript,SIGNAL(KeyEvent(QString)),SLOT(DeviceI nputEvent(QString))); 31. connect(recordScript,SIGNAL(Error(QString)),SLOT(Error(QStr ing))); 32. 33. connect(recordScript,SIGNAL(StartRecord()),SLOT(StartRecord Event())); 34. connect(recordScript,SIGNAL(StopRecord()),SLOT(StopRecordEv ent())); 35. 36. connect(recordScript,SIGNAL(StartRun()),SLOT(StartRunEvent( ))); 37. connect(recordScript,SIGNAL(StopRun()),SLOT(StopRunEvent()) ); 38. 39. connect(recordScript,SIGNAL(StartRun()),runScript,SLOT(Next Row())); 40. connect(recordScript,SIGNAL(StopRun()),runScript,SIGNAL(Sto pExecuteScript())); 41. 42. connect(runScript,SIGNAL(StopRun()),recordScript,SIGNAL(Sto pRun())); 43. 44. 45. connect(this,SIGNAL(PauseRecordScript()),recordScript,SLOT( PauseRecord())); 46. connect(this,SIGNAL(ResumeRecordScript()),recordScript,SLOT (ResumeRecord())); 47. 48. hotKeyDialog=new HotKeyDialog(parent); 49. 50. connect(recordScript,SIGNAL(StartRun()),hotKeyDialog,SLOT(S tartRun())); 51. connect(recordScript,SIGNAL(StopRun()),hotKeyDialog,SLOT(St opRun())); 52. 53. 54. listView->setIconSize(QSize(20,15)); 55. listView->setModel(standardItemModel); 56. 57. deleteAction=new QAction(tr("Delete"),this); 58. deleteAction->setVisible(false); 59. connect(deleteAction,SIGNAL(triggered()),SLOT(DeleteLine()) ); 60. listView->addAction(deleteAction); 61. listView->setContextMenuPolicy(Qt::ActionsContextMenu); 62.} 63. 64. 65.ShowScript::~ShowScript() 66.{ 67. delete recordScript; 68. delete listView; 69. delete standardItemModel; 70. delete hotKeyDialog; 71.} 72. 73. 74.void ShowScript::ShowHotKeyDialog()//显示热键对话框 75.{ 76. hotKeyDialog->show(); 77.} 78. 79. 80.void ShowScript::DeleteLine()//删除一行脚本 81.{ standardItemModel->takeRow(listView->currentIndex().row());82. 83.} 84. 85. void ShowScript::DeviceInputEvent(const QString &key)//设备输入86. 事件 87.{ 88. 89. bufferScript.append(key); } 90. 91. 92. 93.void ShowScript::SetEditShowMode(bool mode)//设置编辑脚本 94.{ 95. emit SetCheckBox(mode); 96. editMode=mode; 97. if(mode) 98. listView->setEditTriggers(QAbstractItemView::AllEdi tTriggers); 99. else 100. listView->setEditTriggers(QAbstractItemView::N oEditTriggers); 101. 102. this->ShowScriptListView(); 103. 104. deleteAction->setVisible(editMode); 105. 106. } 107. 108. 109. void ShowScript::ShowScriptListView(void)//显示脚本数据 110. { 111. 112. standardItemModel->clear();//清空列表数据 113. 114. for(QStringList::ConstIterator begin=bufferScript.begi n();begin!=bufferScript.end();++begin) 115. { 116. if(begin->contains("Move")&&!editMode) 117. continue; 118. 119. if(!begin->isEmpty()) 120. { Qt::GlobalColor background1;//设置背景颜色紫121. 色 122. Qt::GlobalColor background2; 123. 124. if(begin->contains("Key")) { 125. 126. deviceImagePath=":/image/key.jpg"; 127. background1=Qt::yellow;//设置背景颜色紫 色 128. background2=Qt::green;//绿色 }else 129. 130. { 131. deviceImagePath=":/image/mouse.jpg"; 132. background1=Qt::cyan;//蓝色 133. background2=Qt::magenta;//粉红色 134. } 135. 136. 137. QStandardItem *item=new QStandardItem(QIcon(de viceImagePath),*begin); 138. 139. QLinearGradient linearGrad(QPointF(0,0),QPoint F(150,150)); 140. linearGrad.setColorAt(0,background1); 141. linearGrad.setColorAt(1,background2); 142. 143. item->setBackground(QBrush(linearGrad)); 144. 145. if(begin->contains("//")) 146. { 147. item->setFont(QFont("",10,QFont::DemiBold) ); 148. item->setForeground(QBrush(qRgb(243,105,71 )));// 设置前景色为紫色 149. } 150. 151. 152. standardItemModel->appendRow(item); 153. 154. listView->verticalScrollBar()->setValue(standa rdItemModel->rowCount()); 155. } 156. } 157. } 158. 159. 160. 161. void ShowScript::StartRecordEvent()//开始录制脚本 162. { statusBar->showMessage(tr("Script Recording,Please Ent163. er F12 Stop Record...")); 164. standardItemModel->clear(); 165. 166. bufferScript.clear(); 167. 168. newlyScript=true; 169. } 170. 171. void ShowScript::StopRecordEvent()//停止录制 172. { 173. statusBar->showMessage(tr("Record Script Is Stop,Pleas e Enter F12 Resume Record...")); 174. this->SetEditShowMode(false); 175. this->HintSaveNewScript(); 176. } 177. 178. void ShowScript::StartRunEvent()//开始运行脚本事件 179. { 180. statusBar->showMessage(tr("Script Is Runing,Please E nter Shift+F12 Stop Run....")); 181. } 182. 183. void ShowScript::StopRunEvent()//停止运行脚本事件 184. { 185. statusBar->showMessage(tr("Script Is Stop,Please Enter S hift+F12 Continue Run...")); 186. } 187. 188. void ShowScript::Error(const QString &exception)//错误信 息 189. { 190. QMessageBox::warning(this,tr("Error"),exception); 191. } 192. 193. void ShowScript::HintSaveNewScript()//保存新的脚本的脚本提 示 194. { 195. if(newlyScript) { 196. 197. if(QMessageBox::question(this,tr("Save New Script? "),tr("Do You Want To Save New Script?"),QMessageBox::Yes,QMess ageBox::No)==QMessageBox::Yes) 198. { this->SaveScript(); 199. 200. standardItemModel->clear(); 201. bufferScript.clear(); } 202. 203. newlyScript=false; 204. 205. } 206. 207. } 208. 209. void ShowScript::SaveScript(void)//保存脚本 210. { 211. if(recordScript->IsRecord()) 212. { 213. Error(tr("Script Recording....")); 214. return; 215. } 216. 217. if(bufferScript.count()==0) 218. { 219. Error("Script Is Empty!!"); 220. return; 221. } 222. 223. QString path=QFileDialog::getSaveFileName(this,tr("Sav e Script"),"/home/Script/",tr("Text files(*.txt)")); 224. 225. if(path.isEmpty()) 226. return; 227. 228. QFile file(path); 229. if(!file.open(QIODevice::WriteOnly|QIODevice::Text)) 230. { 231. this->Error(file.errorString()); 232. return; 233. } 234. 235. QTextStream out(&file); 236. for(QStringList::ConstIterator begin=bufferScript.begin237. ();begin!=bufferScript.end();++begin)//遍历数据 238. { 239. out<<*begin<<"\n"; 240. } 241. 242. file.close(); 243. } 244. 245. 246. 247. void ShowScript::ReadScript(const QString &path)//读取脚 本 248. { 249. standardItemModel->clear(); 250. bufferScript.clear(); 251. this->HintSaveNewScript(); 252. 253. statusBar->showMessage(tr("Sctipr File Loading.....")) ; 254. 255. if(recordScript->IsRecord()) 256. { 257. Error(tr("Script Recording....")); 258. return; 259. } 260. 261. if(path.isEmpty()) 262. return; 263. 264. QFile file(path); 265. if(!file.open(QIODevice::ReadOnly|QIODevice::Text)) 266. { 267. Error(file.errorString()); 268. return; 269. } 270. 271. QTextStream in(&file); 272. while(!in.atEnd()) 273. { 274. bufferScript.append(in.readLine()); 275. } 276. 277. file.close(); 278. 279. this->SetEditShowMode(false); 280. statusBar->showMessage(tr("Script File Load Finish!")) ; 281. } [cpp] view plaincopy 1. [cpp] view plaincopy 1. 下面是热键的实现:hotkey.cpp [cpp] view plaincopy 1. #include "hotkeydialog.h" 2. 3. QStringList HotKeyDialog::systemKey=QStringList()<setupUi(this); 15. QRegExp reg("[0-9]\.{1,10}"); QValidator *validator=new QRegExpValidator(reg,this); 16. 17. ui->lineEdit->setValidator(validator); 18. 19. ui->SystemKeyComboBox->addItems(systemKey); 20. ui->letterKeyComboBox->addItems(letterKey); 21. 22. tableView=new QTableView(parent); 23. tableView->setGeometry(500,60,250,600); standardItemModel=new QStandardItemModel(this); 24. 25. standardItemModel->setHorizontalHeaderLabels(QStringList()< setModel(standardItemModel); 28. standardItemModel->setColumnCount(2); 29. tableView->setColumnWidth(0,150); 30. tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlways Off); 31. tableView->setSelectionBehavior(QAbstractItemView::SelectRo ws); 32. tableView->setEditTriggers(QAbstractItemView::NoEditTrigger s); 33. 34. deleteHotKey=new QAction(tr("Delete"),this); 35. connect(deleteHotKey,SIGNAL(triggered()),SLOT(DeteleHotKey( ))); 36. 37. tableView->addAction(deleteHotKey); 38. tableView->setContextMenuPolicy(Qt::ActionsContextMenu); 39. 40. this->Read(); 41.} 42. 43. 44.HotKeyDialog::~HotKeyDialog() 45.{ 46. this->FreeMemory(); 47.} 48. 49. 50.void HotKeyDialog::FreeMemory()//释放内存 51.{ 52. for(QVector::Iterator begin=hotKeyList.beg in();begin!=hotKeyList.end();++begin) 53. { delete *begin; 54. 55. } 56. 57. if(!hotKeyList.isEmpty()) 58. hotKeyList.clear(); } 59. 60. 61. void HotKeyDialog::on_buttonBox_accepted() 62. 63.{ QString hotKey="Key:",letterKey,Interval="Time:"; 64. 65. bool error=false; 66. 67. if(ui->SystemKeyComboBox->currentIndex()>0) 68. hotKey+=ui->SystemKeyComboBox->currentText()+"+"; 69. 70. 71. if(ui->letterKeyComboBox->currentIndex()>0) 72. letterKey+=ui->letterKeyComboBox->currentText()+","; 73. else 74. error=true; 75. 76. Interval+=QString::number(ui->lineEdit->text().toDouble()*1 000)+";"; 77. 78. 79. 80. if(error) 81. { 82. QMessageBox::warning(this,tr("Add Hot Key Error"),tr("E rror,Please Retry Add Hot Key!")); 83. return; 84. } 85. 86. this->ShowContent(hotKey+letterKey,Interval); 87. } 88. 89. 90.void HotKeyDialog::ShowContent(const QString &key,const QString &time)//显示内容 91.{ 92. QStandardItem *keyItem=new QStandardItem(key); 93. QStandardItem *interval=new QStandardItem(time); 94. int rowCount=standardItemModel->rowCount(); 95. 96. QLinearGradient linearGradient(QPointF(0,0),QPointF(150,150 )); 97. 98. if(rowCount%2) linearGradient.setColorAt(0,Qt::yellow); 99. 100. else 101. linearGradient.setColorAt(0,Qt::darkYellow); 102. 103. keyItem->setBackground(QBrush(linearGradient)); interval->setBackground(QBrush(linearGradient)); 104. 105. 106. standardItemModel->setItem(rowCount,0,keyItem); 107. standardItemModel->setItem(rowCount,1,interval); 108. standardItemModel->setVerticalHeaderItem(rowCount-1,NU LL); 109. 110. } 111. 112. 113. void HotKeyDialog::StartRun() //开始运行脚本 114. { 115. for(int i=0;irowCount();i++) 116. { 117. QStandardItem *key=standardItemModel->item(i,0); 118. QStandardItem *interval=standardItemModel->item(i, 1); 119. AnalysisScript *script=new AnalysisScript(key->tex t()+interval->text(),true); 120. script->SetLoopWhile(true); 121. hotKeyList.append(script); 122. } 123. 124. deleteHotKey->setVisible(false); 125. this->Save(); 126. } 127. 128. 129. void HotKeyDialog::StopRun()//停止运行脚本 130. { 131. this->FreeMemory(); 132. deleteHotKey->setVisible(true); 133. } 134. 135. 136. void HotKeyDialog::DeteleHotKey()//删除热键 137. { 138. standardItemModel->takeRow(tableView->currentIndex().r ow()); this->Save(); 139. 140. } 141. 142. 143. void HotKeyDialog::Save()//保存热键 { 144. 145. if(standardItemModel->rowCount()>0) 146. { 147. QFile file("HotKey.txt"); 148. if(!file.open(QIODevice::WriteOnly|QIODevice::Text )) 149. return; 150. QTextStream out(&file); 151. for(int i=0;irowCount();++i) 152. { 153. out<item(i,0)->text()<<"\n "; 154. out<item(i,1)->text()<<"\n "; 155. } 156. file.close(); 157. } 158. } 159. 160. void HotKeyDialog::Read()//读取热键 161. { 162. QFile file("HotKey.txt"); 163. if(!file.open(QIODevice::ReadOnly|QIODevice::Text)) 164. return; 165. 166. QString key,time; 167. QTextStream in(&file); 168. while(!in.atEnd()) 169. { 170. 171. key=in.readLine(); 172. time=in.readLine(); 173. ShowContent(key,time); 174. } 175. 176. file.close(); 177. } 倒计时关机的实现。或者循环脚本关机的实现:.shutdowntask.cpp [cpp] view plaincopy 1. #include "shutdowntask.h" 2. #include 3. 4. ShutdownTask::ShutdownTask(QObject *parent) : 5. QObject(parent),lib("system.dll") 6. { 7. PowerManage=(POWERMANAGE)lib.resolve("PowerManage"); 8. 9. if(!PowerManage) 10. emit Error(tr("Load System.dll Failed")); 11. 12.} 13. 14. 15.void ShutdownTask::Shutdown() 16.{ 17. PowerManage(0); 18.} 19. 20. 21.void ShutdownTask::SetCountDown(const QTime &countTime)//设置倒 计时关机 22.{ 23. int hour=countTime.hour()*3600,minute=countTime.minute()*60 ,second=countTime.second(); 24. 25. countDown=hour+minute+second; 26. connect(&timer,SIGNAL(timeout()),SLOT(CountDown())); 27. timer.start(1000); 28.} 29. 30. void ShutdownTask::CountDown() 31. 32.{ 33. countDown--; 34. if(countDown==0) 35. PowerManage(0); 36. 37. emit ShowCountTime(QTime().addSecs(countDown)); 38.} 39. 40.void ShutdownTask::StopCountDown() { 41. 42. timer.stop(); 43.} 分析脚本实现源码。analisissccript.cpp [cpp] view plaincopy 1. #include "analysisscript.h" 2. 3. QStringList KeyBoard::functionKey=QStringList()<<"F1"<<"F2"<<"F 3"<<"F4"<<"F5"<<"F6"<<"F7"<<"F8"<<"F9"<<"F10"<<"F11"<<"F12"; 4. 5. QStringList KeyBoard::numKey=QStringList()<<"0"<<"1"<<"2"<<"3"< <"4"<<"5"<<"6"<<"7"<<"8"<<"9"; 6. 7. QStringList KeyBoard::letterKey=QStringList()<<"A"<<"B"<<"C"<<" D"<<"E"<<"F"<<"G"<<"H"<<"I"<<"J"<<"K"<<"L"<<"M"<<"N"<<"O"<<"P"< <"Q"<<"R"<<"S"<<"T" 8. <<"U"<<"V"<<"W"<<"X"<<"Y"<<"Z"; 9. 10. 11. 12.AnalysisScript::AnalysisScript(const QString &inputScript,const bool isHotKey):lib("system.dll"),run(true), 13. loopWhile(false),hotKey(isHotKey) 14.{ 15. 16. InputEvent=(INPUTEVENT)lib.resolve("SendEvent"); 17. if(!InputEvent) 18. emit this->Error(tr("Load System.dll Failed")); 19. this->Analysis(inputScript); 20. 21. connect(&timer,SIGNAL(timeout()),SLOT(ExecuteAnalysis())); 22. timer.start(0); 23.} 24. 25. 26. AnalysisScript::~AnalysisScript() { 27. 28. lib.unload();//释放动态链接库 } 29. 30. 31. 32.void AnalysisScript::Analysis(const QString &script)//分析脚 本 33.{ 34. QStringList list=script.split(";",QString::SkipEmptyParts); 35. 36. for(QStringList::Iterator iter=list.begin();iter!=list.end( );++iter) 37. { 38. if(!iter->contains("//"))//过滤注释 39. { 40. 41. QStringList comma=iter->split(",",QString::SkipEmptyPart s); //获取行逗号分隔符 42. 43. 44. QStringList colon=comma[0].split(":",QString::SkipEmpty Parts);//获取冒号分隔符 45. 46. 47. if(colon[0]=="Key")//是否为键盘 48. { 49. 50. this->scriptList.push_back(KeyBoard(colon,comma[1] )); 51. 52. }else if(colon[0]=="Mouse")//是否为鼠标 53. { 54. 55. this->scriptList.push_back(Mouse(colon,comma[1])); 56. 57. } 58. } 59. } 60. this->IDBegin=scriptList.begin(); 61. 62. this->IDEnd=scriptList.end(); 63.} 64. 65. void AnalysisScript::ExecuteAnalysis(void)//开始执行脚本 66. 67.{ 68. if(run)//是否暂停脚本 69. { 70. if(IDBegin!=IDEnd) 71. { 72. if(IDBegin->type==InputDevice::KEYBOARD) 73. { 74. InputEvent(IDBegin->KeyBoard::hotButton,IDBegin- >KeyBoard::button,0,0); 75. 76. if(hotKey) 77. { 78. timer.setInterval(IDBegin->KeyBoard::keyDel ay);//设置延时 79. }else 80. { 81. ++IDBegin; 82. 83. if(IDBegin!=IDEnd) 84. timer.setInterval(IDBegin->KeyBoard::key Delay);//设置延时 85. else 86. timer.setInterval(1); 87. } 88. 89. 90. }else if(IDBegin->type==InputDevice::MOUSE) 91. { 92. InputEvent(0,IDBegin->Mouse::button,IDBegin->Mou se::point.x(),IDBegin->Mouse::point.y()); 93. 94. if(hotKey) 95. { timer.setInterval(IDBegin->Mouse::keyDelay);96. //设置延时 97. }else 98. { 99. ++IDBegin; 100. 101. if(IDBegin!=IDEnd) 102. timer.setInterval(IDBegin->Mouse::k eyDelay);//设置延时 103. else timer.setInterval(1); 104. 105. } 106. 107. } 108. 109. }else if(loopWhile) 110. { 111. IDBegin=scriptList.begin(); 112. 113. }else 114. { 115. timer.stop(); 116. emit ScriptFinish();//发送执行完成信号 117. 118. } 119. } 120. } 121. 122. 123. void AnalysisScript::SetLoopWhile(bool state)//设置永久循 环 124. { 125. loopWhile=state; 126. } 127. 128. 129. void AnalysisScript::StopExecute()//暂停脚本信号 130. { 131. run=!run; 132. } 133. 134. //======================================================== ======================================================== 135. InputDevice::InputDevice() { 136. 137. type=NOKIND; 138. } 139. 140. InputDevice::InputDevice(const KeyBoard &keyBoard) { 141. 142. KeyBoard::button=keyBoard.button; 143. KeyBoard::hotButton=keyBoard.hotButton; KeyBoard::keyDelay=keyBoard.keyDelay; 144. 145. type=KEYBOARD; } 146. 147. 148. InputDevice::InputDevice(const Mouse &mouse) 149. { 150. 151. Mouse::button=mouse.button; 152. Mouse::point=mouse.point; 153. Mouse::keyDelay=mouse.keyDelay; 154. type=MOUSE; 155. } 156. 157. InputDevice& InputDevice::operator=(const KeyBoard &keyBoa rd) 158. { 159. if(this!=&keyBoard) 160. { 161. KeyBoard::button=keyBoard.button; 162. KeyBoard::hotButton=keyBoard.hotButton; 163. KeyBoard::keyDelay=keyBoard.keyDelay; 164. type=KEYBOARD; 165. } 166. return *this; 167. } 168. 169. 170. InputDevice& InputDevice::operator=(const Mouse &mouse) 171. { 172. if(this!=&mouse) 173. { 174. Mouse::button=mouse.button; 175. Mouse::point=mouse.point; 176. Mouse::keyDelay=mouse.keyDelay; 177. type=MOUSE; 178. } return *this; 179. 180. } 181. //======================================================== =================================================== 182. KeyBoard::KeyBoard() 183. 184. { 185. this->button=Qt::Key_0; this->hotButton=static_cast(0x00000000); 186. 187. this->keyDelay=0; } 188. 189. 190. 191. KeyBoard::KeyBoard(const QStringList &script,const QString &time) 192. { 193. if(!script.isEmpty()) 194. { 195. QStringList delay=time.split(":"); 196. this->keyDelay=delay[1].toInt(); 197. 198. QString tempHotButon,tempButton; 199. if(script[1].contains("+"))//是否有组合键 200. { 201. QStringList hotKey=script[1].split("+",QSt ring::SkipEmptyParts);//分解组合键 202. tempHotButon=hotKey[0]; 203. tempButton=hotKey[1]; 204. }else 205. { 206. tempButton=script[1]; 207. } 208. 209. this->AnalysisKeyBoardMask(tempButton,tempHotButon ); 210. } 211. } 212. 213. 214. 215. void KeyBoard::AnalysisKeyBoardMask(const QString &button ,const QString &hotButton)//分析键盘掩码 216. { 217. if(!hotButton.isEmpty()) //判断系统热键 { 218. 219. if(hotButton=="Shift") 220. this->hotButton=Qt::Key_Shift; 221. else if (hotButton=="Ctrl") 222. this->hotButton=Qt::Key_Control; else if(hotButton=="Alt") 223. 224. this->hotButton=Qt::Key_Menu; 225. }else { 226. 227. this->hotButton=static_cast(0x00000000); } 228. 229. 230. int mask=-1; 231. 232. if((mask=letterKey.indexOf(button))>-1) 233. { 234. this->button=static_cast(Qt::Key_A+mask) ; //转换成字符掩码 235. return; 236. } 237. 238. 239. if((mask=numKey.indexOf(button))>-1) 240. { 241. this->button=static_cast(Qt::Key_0+mask); //转换成数字掩码 242. return; 243. } 244. 245. if((mask=functionKey.indexOf(button))>-1)//转换成功能 键 246. { 247. this->button=static_cast(Qt::Key_F1+mask ); 248. return; 249. } 250. 251. if(button=="Tab") 252. { 253. this->button=Qt::Key_Tab; 254. 255. }else if(button=="BackSpace") 256. { 257. this->button=Qt::Key_Back; 258. 259. }else if(button=="Enter") 260. { 261. this->button=Qt::Key_Enter; 262. }else if(button=="CapsLock") 263. 264. { 265. this->button=Qt::Key_CapsLock; 266. 267. }else if(button=="Space") { 268. 269. this->button=Qt::Key_Space; 270. 271. }else if(button=="Esc") 272. { 273. this->button=Qt::Key_Escape; 274. } 275. 276. } 277. 278. //======================================================== ======================================================= 279. 280. Mouse::Mouse() 281. { 282. this->button=Qt::LeftButton; 283. this->keyDelay=0; 284. } 285. 286. Mouse::Mouse(const QStringList &script,const QString &time ) 287. { 288. if(!script.isEmpty()) 289. { 290. QStringList delay=time.split(":"); 291. this->keyDelay=delay[1].toInt(); 292. QString button; 293. QStringList mouse=script[1].split("(",QString::Ski pEmptyParts); 294. button=mouse[0]; 295. QString pos=mouse[1].remove(")"); 296. QStringList mouseXYPos=pos.split("*",QString::Skip EmptyParts); //获取X,Y坐标 297. this->AnalysisMouseMask(button,mouseXYPos); 298. 299. } 300. 301. } 302. void Mouse::AnalysisMouseMask(const QString &button,const303. QStringList &pos)//分析鼠标掩码 304. { this->point.setX(pos[0].toInt());//X..Y坐标 305. 306. this->point.setY(pos[1].toInt()); if(button=="LeftClick") 307. 308. this->button=Qt::LeftButton; 309. 310. else if(button=="RightClick") 311. this->button=Qt::RightButton; 312. 313. else if(button=="Move") 314. this->button=Qt::NoButton; 315. 316. } 下面是HOOK键盘和鼠标的实现: [cpp] view plaincopy 1. /* Replace "dll.h" with the name of your header */ 2. #include "dll.h" 3. HookClass *pHookClass=NULL; 4. 5. bool __stdcall SetupMouseEvent(MOUSEEVENT pMouse) //安装鼠 标驱动 6. { 7. pHookClass->MouseEvent=pMouse; 8. return pHookClass->AttachMouseHook(); 9. 10.} 11. 12.bool __stdcall SetupKeyBoardEvent(KEYBOARDEVENT pKeyBoard)//安 装键盘驱动 13.{ 14. pHookClass->KeyBoardEvent=pKeyBoard; 15. return pHookClass->AttachKeyBoardHook(); 16.} 17. LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lPa18. ram)//鼠标回调函数 19.{ 20. if(wParam==WM_LBUTTONDOWN || wParam==WM_RBUTTONDOWN || wPar am==WM_MOUSEMOVE) { 21. 22. LPMOUSEHOOKSTRUCT mouseDetials=(LPMOUSEHOOKSTRUCT)lPara m; 23. 24. int keyType; if(wParam==WM_LBUTTONDOWN) 25. 26. keyType=0; //判断鼠标按键类型,0为左键,1为右 键 27. else if(wParam==WM_RBUTTONDOWN) 28. keyType=1; 29. else if(wParam==WM_MOUSEMOVE)//鼠标移动 30. keyType=2; 31. 32. pHookClass->MouseEvent(keyType,mouseDetials->pt.x,mous eDetials->pt.y); 33. } 34. 35. return CallNextHookEx(pHookClass->GetMouseHookHandle(),nC ode,wParam,lParam); 36.} 37. 38.LRESULT CALLBACK KeyBoardProc(int nCode, WPARAM wParam, LPARAM lParam) //键盘回调函数 39.{ 40. if(nCode==HC_ACTION&&(wParam==WM_KEYDOWN || wParam==WM_SYSK EYDOWN)) //判断键时候被按下 41. { 42. PKEYBDINPUT pKey=(PKEYBDINPUT)lParam; 43. 44. int hotKey=0; 45. 46. if(GetAsyncKeyState(VK_SHIFT)&0x8000) //判断是 否有组合键 47. hotKey=1; 48. if(GetAsyncKeyState(VK_CONTROL)&0x8000) 49. hotKey=2; 50. if(GetAsyncKeyState(VK_LMENU)&0x8000) 51. hotKey=3; 52. pHookClass->KeyBoardEvent(hotKey,pKey->wVk); 53. 54. } 55. return CallNextHookEx(pHookClass->GetKeyHookHandle(),nCode, wParam,lParam); 56.} 57. 58.HookClass::HookClass(HINSTANCE hMoudle) 59.{ 60. 61. mHook=NULL; kHook=NULL; 62. 63. HInstance=hMoudle; 64.} 65. 66. 67.HookClass::~HookClass () 68.{ 69. this->DetachMouseHook(); 70. this->DetachKeyBoardHook(); 71.} 72. 73. 74.bool HookClass::AttachMouseHook(void)//安装鼠标钩子 75.{ 76. if(mHook==NULL) 77. mHook=SetWindowsHookEx(WH_MOUSE_LL,(HOOKPROC)MouseProc,H Instance,0); 78. return mHook; 79.} 80. 81.bool HookClass::AttachKeyBoardHook(void)//安装键盘钩子 82.{ 83. if(kHook==NULL) 84. kHook=SetWindowsHookEx(WH_KEYBOARD_LL,(HOOKPROC)KeyBoar dProc,HInstance,0); 85. 86. return kHook; 87.} 88. 89.bool HookClass::DetachKeyBoardHook(void)//卸载键盘钩子 90.{ 91. if(kHook!=NULL) 92. return UnhookWindowsHookEx(kHook); 93. return false; } 94. 95. 96.bool HookClass::DetachMouseHook(void)//卸载钩子 97.{ 98. if(mHook!=NULL) return UnhookWindowsHookEx(mHook); 99. 100. return false; 101. } 102. 103. HHOOK HookClass::GetMouseHookHandle(void)const //获取 HOOK句柄 104. { 105. return mHook; 106. } 107. 108. HHOOK HookClass::GetKeyHookHandle(void)const//获取键盘hook 句柄 109. { 110. return kHook; 111. } 112. 113. BOOL APIENTRY DllMain (HINSTANCE hInst /* Library inst ance handle. */ , 114. DWORD reason /* Reason this function is being called. */ , 115. LPVOID reserved /* Not used. */ ) 116. { 117. 118. switch (reason) 119. { 120. case DLL_PROCESS_ATTACH: 121. CoInitialize(NULL); 122. if(pHookClass==NULL) 123. pHookClass=new HookClass(hInst); 124. 125. break; 126. 127. case DLL_PROCESS_DETACH: 128. 129. if(pHookClass) 130. delete pHookClass; 131. break; 132. 133. 134. case DLL_THREAD_ATTACH: 135. CoUninitialize(); 136. // if(pHookClass==NULL) // pHookClass=new HookClass(hInst137. ); 138. 139. 140. break; 141. 142. case DLL_THREAD_DETACH: 143. 144. //if(pHookClass) 145. // delete pHookClass; 146. 147. break; 148. } 149. 150. /* Returns TRUE on success, FALSE on failure */ 151. return TRUE; 152. } 如果使用Qt开发界面,往往离不开QDesktopServices,QDesktopServices不仅 可以打开本地浏览器,而且还可以打开本地文件(夹)等,可以获取桌面、我的 文档、Home等目录。。。好吧,实现比较简单~ 1、打开浏览器网页 QUrl url(QString("www.google.com")); bool is_open = QDesktopServices::openUrl(url); 2、打开本地文件(夹)、可执行程序等 QString local_path = QString("E:/新建文件夹"); //a.txt、a.exe、a.mp3、 a.mp4、a.rmvb等 QString path = QString("file:///") + local_path; bool is_open = QDesktopServices::openUrl(QUrl(path, QUrl::TolerantMode)); 注意:这里local_path可以是文件(夹)路径、可执行程序路径,当为文件 时,会选择默认打开方式进行打开~ 3、获取桌面、我的文档、Home等目录的路径 QString desktop_path = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation); QString document_path = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); QString home_path = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); QString application_path = QDesktopServices::storageLocatio(QDesktopServices::ApplicationsLocation); QString temp_path = QDesktopServices::storageLocation(QDesktopServices::TempLocation); 在这里再罗嗦一点,QProcess也可以打开文件(夹)、可执行程序等 QString local_path = QString("E:\\新建文件夹"); bool is_start = QProcess::startDetached("explorer " + local_path); 以上都经过验证,屡试不爽~ 注: 技术在于交流、沟通,转载请注明出处并保持作品的完整性。 作者:??奋斗ing?孩子` 原文: 。 类QDesktopServices提供的方法访问常用的桌面服务,如浏览器、播放器、电 子邮件客户端、我们使用QDesktopServices::openUrl(url),可以根据指定的 url打开Web浏览器,并返回结果,如果成功返回true,否则返回false。相应 的可以打开文件(夹),可执行程序等~ 如果想要启动其他应用程序使用QProcess,当发生错误时,可以根据指定 的错误描述所发生的错误类型。 描述:在界面启动后,可通过点击按钮启动一个外部指定的程序~ myWidget::myWidget(QWidget *parent) : QWidget(parent) { QPushButton *push_button = new QPushButton(this); connect(push_button, SIGNAL(clicked()), this, SLOT(startProcess())); process = new QProcess(); QObject::connect(process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError (QProcess::ProcessError))); } void myWidget::startProcess() { process->start("E:\\a\\b.exe"); } void myWidget::processError(QProcess::ProcessError error) { switch(error) { case QProcess::FailedToStart: QMessageBox::information(0,"FailedToStart","FailedToStart"); break; case QProcess::Crashed: QMessageBox::information(0,"Crashed","Crashed"); break; case QProcess::Timedout: QMessageBox::information(0,"FailedToStart","FailedToStart"); break; case QProcess::WriteError: QMessageBox::information(0,"Timedout","Timedout"); break; case QProcess::ReadError: QMessageBox::information(0,"ReadError","ReadError"); break; case QProcess::UnknownError: QMessageBox::information(0,"UnknownError","UnknownError"); break; default: QMessageBox::information(0,"default","default"); break; } } 如上:在程序退出时,启动的外部程序不会随着主程序的退出而退出的,如果不希望这种情况发生。 可以在程序退出之前,添加如下代码 if(process) { process->close(); delete process; process = NULL; } 自己完成代码下载: 原文链接:QtEmbedded软键盘输入法实战(附例子) 另:很多功能自己还未完成:比如1、退格键(估计在类里有) 2、(对输入法的隐藏与调出) (本文基于qte4.5, 其他版本酌情阅读,呵呵) 最近看到很多人讨论关于QtEmbedded软键盘的问题, 问的最多的主要集中在以下方面: 1、怎么才能写出不和程序窗口争夺焦点的输入法软键盘 2、怎么把软键盘的键值发送给焦点widget 3、其他关于中文输入法的问题 首先必须明确, 软键盘其实是输入法的一种表现形式, 所以我们在设计实现软键盘时先要去寻找系统中是否提供了输入法的API。 有些人还有疑问:“为什么非得用输入法的API呢, 我用普通的Qt API一样可以实现类似的东西亚~” 但事实并非如此,或许你可以在你的程序中写出一个看起来很像输入法的软键盘窗口, 但要知道普通的QtE API是不能跨进程的, 如果你的系统包含多个程序就必然歇菜~ 相反, 好消息是QtE的输入法API可以保证你的输入法在各个QtE的程序里都可以使用。 ^_^y 限于QtEmbedded文档的不够系统, 可能很多人在大海里捞针样的寻找之后终告放弃,转而采用其他古怪的方法实现软键盘需要的功能。 本文旨在提供入门的输入法框架介绍, 并介绍软键盘的实现方法, 让大家少走一些弯路。 下面将介绍输入法中最重要的基础和框架, 以一个简单的软键盘为蓝本, 后边会捎带提提普通的键盘输入法(如像scim这样的中文输入法)在QtEmbedded中该如何实现。 QtE的输入法框架从较早的QtE2到现在的QtE4没有太多的变化, 一个输入法必须提供一个QWSInputMethod类的实例, 所以在输入法中要实现一个QWSInputMethod类的派生类, 在此派生类中显示和操作软键盘widget并完成与输入法框架的通讯。 QWSServer进程调用QWSServer::setCurrentInputMethod(QWSInputMethod*)激 活该输入法后, 输入法框架会把应用程序的信息发送给QWSInputMethod类, 由QWSInputMethod的虚函数来处理。 所以最核心的部分变成怎样去实现一个QWSInputMethod的派生类,另外怎么让你的软键盘窗口能和程序输入窗口和QWSInputMethod和 平共存。 下面这篇QtE的文档提及了如何解决本文开头提出的第一个问题: 其核心是软键盘widget需要设置Qt::Tool属性, 以保证它不和焦点窗体争夺焦点 关于第二个问题可以在QWSInputMethod类的文档中找到大部分答案。 QWSInputMethod提供的sendPreeditString方法负责将预处理的文本发送给焦点窗体, 一般情况下编辑器会将此文本显示为带下划线或虚线的文本, 表示这是编辑过程中的半成品; 然后 QWSInputMethod::sendCommitString函数负责发送最终用户确认的文本给编辑框。 解决了这两个问题我们就可以写出一个简单的软键盘输入 法了, 呵呵, 可能还有人不相信软键盘如此容易实现, 所以笔者提供了一个小的软键盘例子演示如何解决上面两个问题。 这个例子很简单, 包含main.cpp和mainwin.*代表qte的server进程, 而imframe.*则是QWSInputMethod的派生类, inputwidget.*则是软键盘窗体。 程序里还用到了以前blog中介绍的QSignalMapper类, 如果对此类不熟悉的同学看看这篇帖子扫扫盲。 其他不明白的可以blog或bbs留言。 imframe.tar QWSInputMethod派生类还应该去实现 updateHandler虚函数,该虚函数是输入法框架和输入法之间的桥梁, 专门向输入法发送一些状态信息, 比如在焦点离开或进入编辑框时updateHandler函数就会被调用到, 在这里加入你的输入法的处理可以实现在适当时机显示或隐藏输入法widget等功能。 笔者的例子里也重写了这个函数, 但没写什么实用的功能,只是加了输入法的清空操作。 (懒了,不想写code) 本例子基于QtEmbedded 4.5 开发,可以在qvfb环境运行。 其他版本的输入法程序架构类似, 只是QWSInputMethod类的API差别可能会比较大,以各个版本的文档为准。 上面介绍的是最简单的软键盘输入法, 如果你要实现一个像scim那样的键盘输入法或者触摸屏手写输入法则要复杂得多, 最重要的是如何在焦点窗体之前接收用户的输入, 这里就要用到 QWSInputMethod::filter虚函数。 这里不打算对输入法做过多的介绍了, 大家多看文档。 如果看遍文档仍然有弄不明白的地方, 这时你就需要找个好例子了。 推荐个Qtopia带的输入法, 在Qtopia或QtExtended源码包的src/3rdparty/plugins/inputmethod/pkim目录下可以找到pkim输入 法, 该输入法功能非常完善, 既有键盘输入法又有手写输入法, 所以是个极佳的开发蓝本。 使用qte2和qte3的同学可以参考qtopia2带的输入法插件。
本文档为【qt 知识点总结】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_083599
暂无简介~
格式:doc
大小:213KB
软件:Word
页数:106
分类:互联网
上传时间:2018-04-30
浏览量:54