Qt常用功能代码
Qt自定义窗体
#include "notitle.h"
#include <QMouseEvent>
#include <QDebug>
#include <qmath.h>
#ifdef __cplusplus //是否在cpp文件中
extern "C"{
#include <windowsx.h>
#include <qt_windows.h>
}
#endif
NoTitle::NoTitle(QWidget *parent):QWidget(parent)
{
this->setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground, true);
}
NoTitle::~NoTitle()
{
}
void NoTitle::mouseMoveEvent(QMouseEvent *ev)
{
if(ev->buttons()&Qt::LeftButton)
{
if(press&&(cursor().shape()==Qt::ArrowCursor))
{
move(ev->globalPos()-startPosition);
ev->accept();
}
}
else
{
ev->ignore();
}
}
void NoTitle::mousePressEvent(QMouseEvent *ev)
{
if(ev->button()==Qt::LeftButton)
{
startPosition=ev->globalPos()-geometry().topLeft();
press=true;
ev->accept();
}
else
{
ev->ignore();
}
}
void NoTitle::mouseReleaseEvent(QMouseEvent *ev)
{
if(ev->button()==Qt::LeftButton)
{
press=false;
ev->accept();
}
else
{
ev->ignore();
}
}
bool NoTitle::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
int m_nBorder=5;
bool trigger=false;
MSG *param=static_cast<MSG *>(message);
switch(param->message)
{
case WM_NCHITTEST:
{
int nX=GET_X_LPARAM(param->lParam)-this->frameGeometry().x();
int nY=GET_Y_LPARAM(param->lParam)-this->frameGeometry().y();
if((nX>0)&&(nX<m_nBorder))
{
*result=HTLEFT;
trigger=true;
}
if((nX>this->width()-m_nBorder)&&(nX<this->width()))
{
*result=HTRIGHT;
trigger=true;
}
if((nY>0)&&(nY<m_nBorder))
{
*result=HTTOP;
trigger=true;
}
if((nY>this->height()-m_nBorder)&&(nY<this->height()))
{
*result=HTBOTTOM;
trigger=true;
}
if((nX>0)&&(nX<m_nBorder)&&(nY>0)&&(nY<m_nBorder))
{
*result=HTTOPLEFT;
trigger=true;
}
if((nX>this->width()-m_nBorder)&&(nX<this->width())&&(nY>0)&&(nY<m_nBorder))
{
*result=HTTOPRIGHT;
trigger=true;
}
if((nX>0)&&(nX<m_nBorder)&&(nY>this->height()-m_nBorder)&&(nY<this->height()))
{
*result=HTBOTTOMLEFT;
trigger=true;
}
if((nX>this->width()-m_nBorder)&&(nX<this->width())&&(nY>this->height()-m_nBorder)&&(nY<this->height()))
{
*result=HTBOTTOMRIGHT;
trigger=true;
}
if(trigger)
{
return true;
}
return QWidget::nativeEvent(eventType, message, result);;
}
}
return QWidget::nativeEvent(eventType, message, result);
}
QCommandLineParser, Qt命令行参数处理
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName("my-copy-program");
QCoreApplication::setApplicationVersion("1.0");
QCommandLineParser parser;
parser.setApplicationDescription("Test helper");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));
// A boolean option with a single name (-p)
QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy"));
parser.addOption(showProgressOption);
// A boolean option with multiple names (-f, --force)
QCommandLineOption forceOption(QStringList() << "f" << "force",
QCoreApplication::translate("main", "Overwrite existing files."));
parser.addOption(forceOption);
// An option with a value
QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
QCoreApplication::translate("main", "Copy all source files into <directory>."),
QCoreApplication::translate("main", "directory"));
parser.addOption(targetDirectoryOption);
// Process the actual command line arguments given by the user
parser.process(app);
const QStringList args = parser.positionalArguments();
// source is args.at(0), destination is args.at(1)
bool showProgress = parser.isSet(showProgressOption);
bool force = parser.isSet(forceOption);
QString targetDir = parser.value(targetDirectoryOption);
// ...
}
win32混合编程获取文件图标
QIcon FileTransferWidget::getFileIcon(QString fileName) //win32混合编程获取文件图标
{
QIcon fileIcon=this->style()->standardIcon(QStyle::StandardPixmap(42));
if(!fileName.isEmpty())
{
std::string str="file";
int index=fileName.lastIndexOf(".");
if(index>=0)
{
QString suffix=fileName.mid(index);
str=suffix.toUtf8().constData();
}
LPCSTR name=str.c_str();
SHFILEINFOA info;
if(SHGetFileInfoA(name, FILE_ATTRIBUTE_NORMAL, &info, sizeof(info), SHGFI_SYSICONINDEX|SHGFI_USEFILEATTRIBUTES|SHGFI_ICON))
{
HICON icon=info.hIcon;
fileIcon=QIcon(QtWin::fromHICON(icon));
}
}
return fileIcon;
}
使用系统默认程序打开文件
void FileTransferWidget::confirmExecutableOpen()
{
QFileInfo file(filePath);
static const QStringList dangerousExtensions = { "app", "bat", "com", "cpl", "dmg", "exe", "hta", "jar","js", "jse", "lnk", "msc",
"msh", "msh1", "msh1xml", "msh2", "msh2xml", "mshxml", "msi", "msp", "pif", "ps1", "ps1xml", "ps2", "ps2xml", "psc1", "psc2", "py",
"reg", "scf", "sh", "src", "vb", "vbe", "vbs", "ws", "wsc", "wsf", "wsh" };
if (dangerousExtensions.contains(file.suffix()))
{
if (QMessageBox::warning(FriendList::friendlist->currentShowChatWindowData->chatwindow,"执行文件", "你要执行文件吗?",
QMessageBox::Ok,QMessageBox::Cancel)!=QMessageBox::Ok)
return;
// The user wants to run this file, so make it executable and run it
QFile(file.filePath()).setPermissions(file.permissions() | QFile::ExeOwner | QFile::ExeUser |
QFile::ExeGroup | QFile::ExeOther);
QProcess::startDetached(file.filePath());
}
else
{
QDesktopServices::openUrl(QUrl::fromLocalFile(file.filePath()));
}
}
打开文件位置和光标到当前文件
QFileInfo fi(filePath);
QStringList list;
list.append("/select,"+fi.absoluteFilePath().replace("/", "\\"));
QProcess::startDetached("explorer.exe", list);
//QDesktopServices::openUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
return;
qt配置文件 QStting类
1.创建QSetting类, 设置编码格式。
QSettings s(path, QSettings::IniFormat); //path是指定创建的路径.
QSetting::IniFormat 配置文件格式如下:
QSettings::NativeFormat 0 Store the settings using the most appropriate storage format for the platform. On Windows,
QSettings::IniFormat 1 Store the settings in INI files.
QSettings::InvalidFormat 16 Special value returned by registerFormat().
s.setIniCodec("UTF-8"); //设置编码
s.clear() //清空配置文件内容
2.写入数值到文件,路径为path
void MainWindow::writeSettings()
{
QSettings settings("path", QSettings::IniFormat);
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
3.读取数值到变量, 文件路径为path
void MainWindow::readSettings()
{
QSettings settings("path", QSettings::IniFormat);
settings.beginGroup("MainWindow");
resize(settings.value("size", QSize(400, 400)).toSize());
move(settings.value("pos", QPoint(200, 200)).toPoint());
settings.endGroup();
}
4.以数组方式写入
struct Login {
QString userName;
QString password;
};
QList<Login> logins;
...
QSettings settings;
settings.beginWriteArray("logins");
for (int i = 0; i < logins.size(); ++i) {
settings.setArrayIndex(i);
settings.setValue("userName", list.at(i).userName);
settings.setValue("password", list.at(i).password);
}
settings.endArray();
5.以数组方式读取
struct Login {
QString userName;
QString password;
};
QList<Login> logins;
...
QSettings settings;
int size = settings.beginReadArray("logins");
for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
Login login;
login.userName = settings.value("userName").toString();
login.password = settings.value("password").toString();
logins.append(login);
}
settings.endArray();
树形列表递归选择
#include "chechfriendwidget.h"
#include <QVBoxLayout>
#include <QDebug>
#include <QtWidgets/QHeaderView>
ChechFriendWidget::ChechFriendWidget(QWidget *parent) :QWidget(parent)
{
QHBoxLayout *layout=new QHBoxLayout(this);
layout->setContentsMargins(0, 9,0, 0);
treeView =new QTreeView(this);
treeModel=new QStandardItemModel(treeView);
parentItem=treeModel->invisibleRootItem();
parentItem->setCheckable(true);
parentItem->setEditable(false);
treeView->setModel(treeModel);
treeView->header()->setVisible(false);
treeView->header()->setCascadingSectionResizes(true);
connect(treeModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(treeItemChanged(QStandardItem*)));
treeView->setStyleSheet("QTreeView{icon-size: 20px}");
layout->addWidget(treeView);
}
ChechFriendWidget::~ChechFriendWidget()
{
}
void ChechFriendWidget::treeItemChanged(QStandardItem *item)
{
if(item==nullptr)
return;
emit itemChanget();
if(item->isCheckable())
{
Qt::CheckState state=item->checkState();
if(item->hasChildren())
{
if(state!=Qt::PartiallyChecked)
{
treeItemCheckAllChild(item, (state==Qt::Checked)? true: false);
}
}
else
{
treeItemCheckChildChanged(item);
}
}
}
void ChechFriendWidget::treeItemCheckAllChild(QStandardItem *item, bool check)
{
if(item==nullptr)
return;
int rowCount=item->rowCount();
for(int i=0; i<rowCount; i++)
{
QStandardItem *childItem=item->child(i);
treeItemCheckAllChild(childItem, check);
}
if(item->isCheckable())
item->setCheckState(check? Qt::Checked: Qt::Unchecked);
}
void ChechFriendWidget::treeItemCheckChildChanged(QStandardItem *item)
{
if(item==nullptr)
return;
Qt::CheckState siblingState=checkSibling(item);
QStandardItem * parentItem=item->parent();
if(nullptr==parentItem)
return;
if(Qt::PartiallyChecked==siblingState)
{
if(parentItem->isCheckable())
parentItem->setCheckState(Qt::PartiallyChecked);
}
else if(Qt::Checked==siblingState)
{
if(parentItem->isCheckable())
parentItem->setCheckState(Qt::Checked);
}
else
{
if(parentItem->isCheckable())
parentItem->setCheckState(Qt::Unchecked);
}
treeItemCheckChildChanged(parentItem);
}
Qt::CheckState ChechFriendWidget::checkSibling(QStandardItem *item)
{
QStandardItem *parent=item->parent();
if(nullptr==parent)
return item->checkState();
int brotherCount=parent->rowCount();
int checkedCount(0), unCheckedCount(0);
Qt::CheckState state;
for(int i=0; i<brotherCount; ++i)
{
QStandardItem *siblingitem=parent->child(i);
state=siblingitem->checkState();
if(Qt::PartiallyChecked==state)
{
return Qt::PartiallyChecked;
}
else if(Qt::Unchecked==state)
++unCheckedCount;
else
++checkedCount;
if(checkedCount>0&&unCheckedCount>0)
{
return Qt::PartiallyChecked;
}
}
if(unCheckedCount>0)
{
return Qt::Unchecked;
}
return Qt::Checked;
}
QStandardItem * ChechFriendWidget::getRootItem()
{
return this->parentItem;
}
void ChechFriendWidget::addItem(QStandardItem *parentItem, QStandardItem *childItem, QString groupName)
{
childItem->setCheckable(true);
childItem->setEditable(false);
parentItem->appendRow(childItem);
}
QList<QString > ChechFriendWidget::getAllChlidPitchName(QStandardItem * item) //recursion to find name of child
{
QList<QString> nameList;
if(item==nullptr)
return nameList;
if(item->hasChildren())
{
if(item->checkState()!=Qt::Unchecked||item==parentItem)
{
int rowCount=item->rowCount();
for(int i=0; i<rowCount; i++)
{
QStandardItem *childItem=item->child(i);
nameList.append(getAllChlidPitchName(childItem));
}
}
}
else
{
if(item->checkState()==Qt::Checked)
{
nameList.append(item->text());
}
}
return nameList;
}
void ChechFriendWidget::clearAllChildItem(QStandardItem *parentItem)
{
if(parentItem==nullptr)
return;
if(parentItem->hasChildren())
{
int rowCount=parentItem->rowCount();
for(int i=0; i<rowCount; i++)
{
parentItem->removeRow(i);
}
}
}
USB热插拔监测
MainWindow:: MainWindow ( QWidget * parent) : QWidget ( parent)
{
static const GUID GUID_DEVINTERFACE_LIST[ ] = {
{ 0xA5DCBF10 , 0x6530 , 0x11D2 , { 0x90 , 0x1F , 0x00 , 0xC0 , 0x4F , 0xB9 , 0x51 , 0xED } } ,
} ;
HDEVNOTIFY hDevNotify;
DEV_BROADCAST_DEVICEINTERFACE NotifacationFiler;
ZeroMemory ( & NotifacationFiler, sizeof ( DEV_BROADCAST_DEVICEINTERFACE) ) ;
NotifacationFiler. dbcc_size = sizeof ( DEV_BROADCAST_DEVICEINTERFACE) ;
NotifacationFiler. dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
for ( int i = 0 ; i < sizeof ( GUID_DEVINTERFACE_LIST) / sizeof ( GUID) ; i++ ) {
NotifacationFiler. dbcc_classguid = GUID_DEVINTERFACE_LIST[ i] ;
hDevNotify = RegisterDeviceNotification ( ( HANDLE) this - > winId ( ) , & NotifacationFiler, DEVICE_NOTIFY_WINDOW_HANDLE) ;
}
}
MainWindow:: ~ MainWindow ( )
{ }
bool MainWindow:: nativeEvent ( const QByteArray & eventType, void * message, long * result)
{
MSG* msg = reinterpret_cast < MSG* > ( message) ;
int msgType = msg- > message;
if ( msgType== WM_DEVICECHANGE)
{
PDEV_BROADCAST_HDR lpdb = ( PDEV_BROADCAST_HDR) msg- > lParam;
switch ( msg- > wParam) {
case DBT_DEVICEARRIVAL:
if ( lpdb- > dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = ( PDEV_BROADCAST_VOLUME) lpdb;
if ( lpdbv- > dbcv_flags == 0 )
{
}
}
if ( lpdb- > dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE)
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = ( PDEV_BROADCAST_DEVICEINTERFACE) lpdb;
emit addUsb ( QString:: fromStdWString ( pDevInf- > dbcc_name) ) ;
}
break ;
case DBT_DEVICEREMOVECOMPLETE:
if ( lpdb- > dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = ( PDEV_BROADCAST_VOLUME) lpdb;
if ( lpdbv- > dbcv_flags == 0 )
{
qDebug ( ) << "USB_Removed" ;
}
}
if ( lpdb- > dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE)
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = ( PDEV_BROADCAST_DEVICEINTERFACE) lpdb;
emit removeUsb ( QString:: fromStdWString ( pDevInf- > dbcc_name) ) ;
}
break ;
}
}
return false ;
}