异度部落格

学习是一种生活态度。

0%

这个软件用于计算文件夹中图片所占空间大小

程序很短,直接看代码吧

main.cpp

#include <QtGui>
#include <iostream>
#include <string>
/**
计算文件中图片所占大小
*/
qlonglong imageSpaceCompute(const QString &path)
{
QDir dir(path);
qlonglong size = 0;
QStringList filters;
foreach(QByteArray format,QImageReader::supportedImageFormats())
filters += "*." + format;
foreach(QString file, dir.entryList(filters,QDir::Files)) //entryList 返回文件夹下满足条件的文件名列表
size += QFileInfo(dir,file).size();
//递归,计算子目录中的图片大小
foreach (QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
size += imageSpaceCompute(path + QDir::separator() + subDir);
return size;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString path = QDir::currentPath();
std::cout << "Space used by imaged in" << qPrintable(path)
<< " and its subdirectories is " << (imageSpaceCompute(path) / 1024) << " KB" << std::endl;
return 0;
}

要是不能运行看看项目配置文件,这里附上我的

QT       = core gui xml
TARGET = ImageSpaceCompute
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app

SOURCES += main.cpp

软件截图:

image

最近学习 Qt4 的数据库编程方面,早上安装了下 MySQL,这里写 Qt4 连接 MySQL 的方法

首先,自己先去建立一个数据库名为,DB_Name

然后,自己可以尝试下连接,利用 mysql-admin 是个很好用的工具,保证数据连接是没有问题的,这里用的 Server Name 就用本地的吧(localhost)

保证数据库连接没问题以后,就可以参考下这下面的代码了(仅供参考,有问题请来信),我把它写成函数的形式,方便以后调用

bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("DB_Name");
db.setUserName("root");
db.setPassword("123456");
if (!db.open()) {
QMessageBox::warning(0, QObject::tr("Database Error"),
db.lastError().text());
return false;
}
return true;
}

Sever Name:localhost 使用本地连接

数据库名:DB_Name

登录账户:root

密码:123456

最近太忙了,都没怎么看 Qt 鄙视下自己....

不说了,放代码

symbolpicker.h

#ifndef SYMBOLPICKER_H
#define SYMBOLPICKER_H
#include <QtGui/QDialog>
#include <QMap>
class QDialogButtonBox;
class QIcon;
class QListWidget;
namespace Ui
{
class SymbolPicker;
}
class SymbolPicker : public QDialog
{
Q_OBJECT
public:
SymbolPicker(const QMap<int,QString> &symbolMap,QWidget *parent = 0);
~SymbolPicker();
int selected() const {return id;}
void done(int result);
private:
Ui::SymbolPicker *ui;
QIcon iconForSymbol(const QString &symbolName);
QListWidget *listWidget;
QDialogButtonBox *buttonBox;
int id;
};
#endif // SYMBOLPICKER_H

symbolpicker.cpp

#include<QtGui>
#include "symbolpicker.h"
#include "ui_symbolpicker.h"
SymbolPicker::SymbolPicker(const QMap<int,QString> &symbolMap,QWidget *parent)
: QDialog(parent), ui(new Ui::SymbolPicker)
{
ui->setupUi(this);
id = -1; //设置id默认值
listWidget = new QListWidget;
listWidget->setIconSize(QSize(60,60));
QMapIterator<int,QString> i(symbolMap);
while(i.hasNext()) {
i.next();
QListWidgetItem *item = new QListWidgetItem(i.value(),listWidget);
item->setIcon(iconForSymbol(i.value()));
item->setData(Qt::UserRole,i.key());
}
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok| QDialogButtonBox::Cancel);
connect(buttonBox,SIGNAL(accepted()),this,SLOT(accept()));
connect(buttonBox,SIGNAL(rejected()),this,SLOT(reject()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(listWidget);
layout->addWidget(buttonBox);
setLayout(layout);
setWindowTitle(tr("Symbol Picker"));
}
SymbolPicker::~SymbolPicker()
{
delete ui;
}
void SymbolPicker::done(int result)
{
id = -1;
if (result == QDialog::Accepted) {
QListWidgetItem *item = listWidget->currentItem();
if (item)
id = item->data(Qt::UserRole).toInt();
}
QDialog::done(result);
}
QIcon SymbolPicker::iconForSymbol(const QString &symbolName)
{
QString fileName = ":/images/" + symbolName.toLower();
fileName.replace(' ','-');
return QIcon(fileName);
}

symbolpicker.qrc (资源文件)

<RCC>
<qresource>
<file>images/killua.png</file>
</qresource>
</RCC>

刚开始 icon 显示一直有问题,后来配置了下资源文件就 OK 了...

这个还是练习项视图,用于浏览目录,可以添加新文件夹和删除文件或文件夹

directoryviewer.h

#ifndef DIRECTORYVIEWER_H
#define DIRECTORYVIEWER_H
#include <QtGui/QDialog>
class QDialogButtonBox;
class QDirModel;
class QTreeView;
namespace Ui
{
class DirectoryViewer;
}
class DirectoryViewer : public QDialog
{
Q_OBJECT
public:
DirectoryViewer(QWidget *parent = 0);
~DirectoryViewer();
private slots:
void createDirectory();
void remove();
private:
Ui::DirectoryViewer *ui;
QTreeView *treeView;
QDirModel *model;
QDialogButtonBox *buttonBox;
};
#endif // DIRECTORYVIEWER_H

directoryviewer.cpp

#include <QtGui>
#include "directoryviewer.h"
#include "ui_directoryviewer.h"
/**
构造函数
*/
DirectoryViewer::DirectoryViewer(QWidget *parent)
: QDialog(parent), ui(new Ui::DirectoryViewer)
{
ui->setupUi(this);
//model
model = new QDirModel;
model->setReadOnly(false);
model->setSorting(QDir::DirsFirst | QDir::IgnoreCase | QDir::Name);
//treeView
treeView = new QTreeView;
treeView->setModel(model);
treeView->header()->setStretchLastSection(true);
treeView->header()->setSortIndicator(0,Qt::AscendingOrder);
treeView->header()->setSortIndicatorShown(true);
treeView->header()->setClickable(true);
QModelIndex index = model->index(QDir::currentPath());
treeView->expand(index);
treeView->scrollTo(index);
treeView->resizeColumnToContents(0);
//ButtonBox
buttonBox = new QDialogButtonBox(Qt::Horizontal);
QPushButton *mkdirButton = buttonBox->addButton(tr("&Create Directory"),QDialogButtonBox::ActionRole);
QPushButton *removeButton = buttonBox->addButton(tr("&Remove"),QDialogButtonBox::ActionRole);
buttonBox->addButton(tr("&Quit"),QDialogButtonBox::AcceptRole);

//signal and slot
connect(mkdirButton,SIGNAL(clicked()),this,SLOT(createDirectory()));
connect(removeButton,SIGNAL(clicked()),this,SLOT(remove()));
connect(buttonBox,SIGNAL(accepted()),this,SLOT(accept()));
//Layout
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(treeView);
layout->addWidget(buttonBox);
setLayout(layout);
setWindowTitle(tr("Directory Viewer by Killua"));
}
/**
析构函数
*/
DirectoryViewer::~DirectoryViewer()
{
delete ui;
}
/**
文件夹创建
*/
void DirectoryViewer::createDirectory()
{
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return ;
QString dirName = QInputDialog::getText(this,tr("Create Directory"),tr("Directory Name"));
if (!dirName.isEmpty()) {
if (!model->mkdir(index,dirName).isValid())
QMessageBox::information(this,tr("Create Directory"),tr("Failed to create"));
}
}
/**
删除
*/
void DirectoryViewer::remove()
{
QModelIndex index =treeView->currentIndex();
if (!index.isValid())
return ;
bool ok;
if (model->fileInfo(index).isDir()) {
ok = model->rmdir(index);
} else {
ok = model->remove(index);
}
if (!ok)
QMessageBox::information(this,tr("Remove"),tr("Failed to remvoe"));
}

软件截图: image

这个主要练习项视图的显示并设置了 insert 和 delete 功能


listviewer.h

#ifndef LISTVIEWER_H
#define LISTVIEWER_H
#include <QtGui/QDialog>
class QDialogButtonBox;
class QListView;
class QStringListModel;
namespace Ui
{
class ListViewer;
}
class ListViewer : public QDialog
{
Q_OBJECT
public:
ListViewer(const QStringList &itemList,QWidget *parent = 0);
~ListViewer();
QStringList itemList() const;
private slots:
void insert();
void del();
private:
Ui::ListViewer *ui;
QListView *listView;
QDialogButtonBox *buttonBox;
QStringListModel *model;
};
#endif // LISTVIEWER_H

listviewer.cpp

#include <QtGui>
#include "listviewer.h"
#include "ui_listviewer.h"
ListViewer::ListViewer(const QStringList &itemList,QWidget *parent)
: QDialog(parent), ui(new Ui::ListViewer)
{
ui->setupUi(this);
//model
model = new QStringListModel(this);
model->setStringList(itemList);
//listView
listView = new QListView;
listView->setModel(model);
listView->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); //The QAbstractItemView class provides the basic functionality for item view classes.
//buttonBox
buttonBox = new QDialogButtonBox();
QPushButton *insertButton = buttonBox->addButton(tr("&Insert"),QDialogButtonBox::ActionRole); //ActionRole:Clicking the button causes changes to the elements within the dialog
QPushButton *deleteButton = buttonBox->addButton(tr("&Delete"),QDialogButtonBox::ActionRole);
buttonBox->addButton(QDialogButtonBox::Ok);
buttonBox->addButton(QDialogButtonBox::Cancel);
//signals and slots
connect(insertButton,SIGNAL(clicked()),this,SLOT(insert()));
connect(deleteButton,SIGNAL(clicked()),this,SLOT(del()));
connect(buttonBox,SIGNAL(accepted()),this,SLOT(accept()));
connect(buttonBox,SIGNAL(rejected()),this,SLOT(reject()));
//layout
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(listView);
layout->addWidget(buttonBox);
setLayout(layout);
}
ListViewer::~ListViewer()
{
delete ui;
}
QStringList ListViewer::itemList() const
{
return model->stringList();
}
void ListViewer::insert()
{
int row = listView->currentIndex().row();
model->insertRows(row, 1);
QModelIndex index=model->index(row); //This class is used as an index into item models derived from QAbstractItemModel.
//The index is used by item views, delegates, and selection models to locate an item in the model.
listView->setCurrentIndex(index);
listView->edit(index);
}
void ListViewer::del()
{
model->removeRows(listView->currentIndex().row(),1);
}

用于正则表达式,通配符,完整匹配三种方式

stringmatch.h

#ifndef STRINGMATCH_H
#define STRINGMATCH_H
#include <QtGui/QDialog>
class QComboBox;
class QLabel;
class QLineEdit;
class QListView;
class QSortFilterProxyModel;
class QStringListModel;
namespace Ui
{
class StringMatch;
}
class StringMatch : public QDialog
{
Q_OBJECT
public:
StringMatch(QWidget *parent = 0);
~StringMatch();
private slots:
void reapplyFilter();
private:
Ui::StringMatch *ui;
QStringListModel *sourceModel;
QSortFilterProxyModel *proxyModel;
QListView *listView;
QLabel *filterLabel;
QLabel *syntaxLabel;
QLineEdit *filterLineEdit;
QComboBox *syntaxComboBox;
};
#endif // STRINGMATCH_H

stringmatch.cpp

#include <QtGui>
#include "stringmatch.h"
#include "ui_stringmatch.h"
StringMatch::StringMatch(QWidget *parent)
: QDialog(parent), ui(new Ui::StringMatch)
{
ui->setupUi(this);
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
//sourceModel
sourceModel = new QStringListModel(this);
sourceModel->setStringList(QColor::colorNames());
//proxyModel
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(sourceModel);
proxyModel->setFilterKeyColumn(0);
//listView
listView = new QListView;
listView->setModel(proxyModel);
listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//filter
filterLabel = new QLabel(tr("要匹配的字符串"));
filterLineEdit = new QLineEdit;
filterLabel->setBuddy(filterLineEdit);
//syntax
syntaxLabel = new QLabel("匹配方式选择");
syntaxComboBox = new QComboBox;
syntaxComboBox->addItem("正则表达式",QRegExp::RegExp); //A rich Perl-like pattern matching syntax. This is the default.
syntaxComboBox->addItem("通配符",QRegExp::Wildcard); //This provides a simple pattern matching syntax similar to that used by shells (command interpreters) for "file globbing".
syntaxComboBox->addItem("完全匹配",QRegExp::FixedString); //This is equivalent to using the RegExp pattern on a string in which all metacharacters are escaped using
//当filterLineEdit和syntaxComboBox
connect(filterLineEdit,SIGNAL(textChanged(const QString &)),this,SLOT(reapplyFilter()));
connect(syntaxComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(reapplyFilter()));
//布局
QGridLayout *layout = new QGridLayout;
layout->addWidget(listView,0,0,1,2);
layout->addWidget(filterLabel,1,0);
layout->addWidget(filterLineEdit,1,1);
layout->addWidget(syntaxLabel,2,0);
layout->addWidget(syntaxComboBox,2,1);
setLayout(layout);
setWindowTitle(tr("String Matching"));
}
StringMatch::~StringMatch()
{
delete ui;
}
void StringMatch::reapplyFilter()
{
QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(syntaxComboBox->itemData(
syntaxComboBox->currentIndex()).toInt());
QRegExp regExp(filterLineEdit->text(),Qt::CaseInsensitive,syntax);
proxyModel->setFilterRegExp(regExp);
}

软件截图: image


直到今天才把 Qt4 的中文乱码搞定太尴尬了.......鄙视下自己..... 只要程序中加入 QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale()); QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));

当然要看情况来说,你的环境可能是 GBK 或者其他的...

这个主要是编码的问题,我用的 Ubuntu,貌似 XP 就没有这个问题,蛮发下....

只要在程序种加上这两句:

QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));

具体编码要看具体环境了,可能是 GBK 或者 GB18030 或者其他的.....

PS:今天才搞懂,BS 自己阿....

今天晚上突然想到,前几天写那个 MDI Editor 少了拖拽功能支持,这里补充一下....

主要是对 Editor 类进行补充

在 editor.h 添加

//拖放
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);

在 editor.cpp 添加

/**
拖放的两个Event
*/
void Editor::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction();
}
void Editor::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls();
if(urls.isEmpty())
return ;
QString fileName = urls.first().toLocalFile();
if (fileName.isEmpty())
return ;
if(readFile(fileName))
setWindowTitle(tr("%1").arg(fileName));
}

OK.

PS:晚上才发现,我的工程名居然打错了..mdieditor 打成 mideditor 了...好尴尬...算了不改了,有不影响学习交流

1,把 ubuntu->winboot 文件夹下 wubidr 和 wubidr.mbr 两个文件拷到 C 盘根目录下

2,打开 boot.ini 文件,添加 c:/wubildr.mbf= "Ubuntu",保存修改

PS:boot.ini 在 C 盘的根目录下,要是看不到,进入文件夹选项,去掉“隐藏受保护的操作系统文件”选项,选中"显示所有文件和文件夹",就可以看到 boot.ini 了

下载地址:http://www.libfetion.cn/Linux_demoapp_download.html

如果不能运行安装依赖

sudo apt-get install libcurl3
sudo apt-get install automake libc-dev g++ libcurl4-openssl-dev
sudo apt-get install build-essential
sudo apt-get install libcurl4-dev