目录
1. 拖放操作和剪切板
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDrag>
#include <QDropEvent>
#include <QMouseEvent>
#include <QLineEdit>
#include <QResizeEvent>
#pragma pack(1)
struct ST_INFO
{
bool b;
int i;
};
#pragma pack()
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
QPointF m_pntPress;
bool m_bMimeAdded;
QLineEdit * m_pText1;
QLineEdit * m_pText2;
QLineEdit * m_pText3;
protected:
void mousePressEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
void dropEvent(QDropEvent *);
void dragEnterEvent(QDragEnterEvent *);
void dragMoveEvent(QDragMoveEvent *);
void resizeEvent(QResizeEvent *);
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include <QApplication>
#include <QMimeData>
#include <QDebug>
#include <QTextStream>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setAcceptDrops(true);
m_pText1 = new QLineEdit(this);
m_pText2 = new QLineEdit(this);
m_pText3 = new QLineEdit(this);
}
MainWindow::~MainWindow()
{
delete m_pText1;
delete m_pText2;
delete m_pText3;
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if ((QLineF(event->screenPos(), m_pntPress)
.length() < QApplication::startDragDistance()) || m_bMimeAdded)
{
return;
}
m_bMimeAdded = true;
QDrag *drag = new QDrag(this);
QMimeData *mime = new QMimeData;
drag->setMimeData(mime);
QImage image("E:\\lena.jpg");
drag->setPixmap(QPixmap::fromImage(image).scaled(30, 40));
drag->setHotSpot(QPoint(15, 30));
QByteArray qba;
QString qstrTemp1 = m_pText1->text();
QString qstrTemp2 = m_pText2->text();
bool bTemp;
if(qstrTemp1.contains("true"))
{
bTemp = true;
}
else
{
bTemp = false;
}
ST_INFO stTemp = {bTemp, qstrTemp2.toInt()};
qba.resize(sizeof(stTemp));
memcpy(qba.data(), &stTemp, sizeof(stTemp));
mime->setData(tr("INFO"), qba);
drag->exec();
}
void MainWindow::mousePressEvent(QMouseEvent *e)
{
m_pntPress = e->screenPos();
m_bMimeAdded = false;
}
void MainWindow::dropEvent(QDropEvent *event)
{
MainWindow *source = qobject_cast<MainWindow *>(event->source());
if(source != this)
{
if (event->mimeData()->hasFormat("INFO"))
{
QByteArray pieceData = event->mimeData()->data("INFO");
ST_INFO stTemp;
memcpy(&stTemp, pieceData.data(), sizeof(stTemp));
QString qstrTemp;
QTextStream stream(&qstrTemp, QIODevice::WriteOnly);
stream<<"b = "<<stTemp.b<<" i = "<<stTemp.i;
m_pText3->setText(qstrTemp);
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
event->ignore();
}
}
else
{
event->ignore();
}
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("INFO"))
event->accept();
else
event->ignore();
}
void MainWindow::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("INFO"))
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
event->ignore();
}
}
void MainWindow::resizeEvent(QResizeEvent *e)
{
m_pText1->setGeometry(0,0,width()/2, height()/4);
m_pText2->setGeometry(0, height()/3, width()/2, height()/4);
m_pText3->setGeometry(width()/2, height()*2/3, width()/2, height()/4);
}
2. 网络
QFtp 使用的步骤
ftp->connectToHost("192.168.***.***", 21); // id == 1
ftp->login("wang", "123456"); // id == 2
ftp->cd("/home/wang"); // id == 3
ftp->get("ftp.qdoc"); // id == 4
ftp->close(); // id == 5
常用命令
connectToHost()、login()、close()、list()、cd()、get()、put()、remove()、mkdir()、rmdir()、rename() 和 rawCommand()。
HTTP
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QString>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include <QProgressBar>
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_uploadButton_clicked();
void on_downloadButton_clicked();
void readContent();
void replyFinished(QNetworkReply*);
void loadError(QNetworkReply::NetworkError);
void loadProgress(qint64 bytesSent,qint64 bytesTotal);
private:
Ui::MainWindow *ui;
QNetworkReply *reply;
QProgressBar *progressBar;
QFile *file;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_uploadButton_clicked() //上传文件
{
file = new QFile("../wangzai1.jpg");
file->open(QIODevice::ReadOnly);
QNetworkAccessManager *accessManager1 = new QNetworkAccessManager(this); //在服务器上创建目录
accessManager1->setNetworkAccessible(QNetworkAccessManager::Accessible);
QByteArray data;
QUrl url1("http://192.168.1.166:80/createFolder.php?foldername=upload");
QNetworkRequest request1(url1);
request1.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/octet-stream"));
accessManager1->post(request1, data);
QNetworkAccessManager *accessManager2 = new QNetworkAccessManager(this); //往该目录中上传文件
accessManager2->setNetworkAccessible(QNetworkAccessManager::Accessible);
QByteArray byte_file = file->readAll();
QUrl url2("http://192.168.1.166:80/upload.php?foldername=upload&filename="+ui->lineEdit->text()+".jpg"); //如这里指定的上传文件至HTTP服务器目录中的upload目录中
QNetworkRequest request2(url2);
request2.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
reply = accessManager2->post(request2, byte_file);
progressBar = new QProgressBar();
progressBar->setValue(0);
progressBar->show();
connect(accessManager2,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(loadError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(uploadProgress(qint64 ,qint64)), this, SLOT(loadProgress(qint64 ,qint64)));
}
void MainWindow::on_downloadButton_clicked() //下载文件
{
file = new QFile("/home/zz/" + ui->lineEdit->text() + ".jpg");
file->open(QIODevice::WriteOnly);
QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
accessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
QUrl url("https://img-blog.csdn.net/20170825172648715?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGltb3RoeTkzYnA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
reply = accessManager->get(request);
progressBar = new QProgressBar();
progressBar->setValue(0);
progressBar->show();
connect((QObject *)reply, SIGNAL(readyRead()), this, SLOT(readContent()));
connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(loadError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(downloadProgress(qint64 ,qint64)), this, SLOT(loadProgress(qint64 ,qint64)));
}
void MainWindow::readContent() //下载时向本地文件中写入数据
{
file->write(reply->readAll());
}
void MainWindow::replyFinished(QNetworkReply*) //删除指针,更新和关闭文件
{
if(reply->error() == QNetworkReply::NoError)
{
reply->deleteLater();
file->flush();
file->close();
}
else
{
QMessageBox::critical(NULL, tr("Error"), "Failed!!!");
}
}
void MainWindow::loadProgress(qint64 bytesSent, qint64 bytesTotal) //更新进度条
{
qDebug() << "loaded" << bytesSent << "of" << bytesTotal;
progressBar->setMaximum(bytesTotal); //最大值
progressBar->setValue(bytesSent); //当前值
}
void MainWindow::loadError(QNetworkReply::NetworkError) //传输中的错误输出
{
qDebug()<<"Error: "<<reply->error();
}
QT += core gui
QT += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = HTTP
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
3. 多线程
4. 数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
//QSqlDatabase db = QSqlDatabase::database();允许默认链接
db.setHostName("acidalia");
db.setDatabaseName("customdb");
db.setUserName("mojito");
db.setPassword("J0a1m8");
bool ok = db.open();
主要是sql语句的用法,各种数据库连接上了都是一样的
5. 界面风格
主要和QPalette有关
QTextBrowser browser;
QColor linkColor(Qt::red);
QString sheet = QString::fromLatin1("a { text-decoration: underline; color: %1 }").arg(linkColor.name());
browser.document()->setDefaultStyleSheet(sheet);
6. 视图/模型
7. 脚本
8. webkit与多媒体
QWebView *view = new QWebView;
view->load(QUrl("https://www.baidu.com/"));
view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
view->show();
简单浏览器:
QT += core gui
QT +=sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET =sqltest
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp\
mainwindow.cpp \
addressbar.cpp \
htmlview.cpp \
tabpage.cpp
HEADERS += mainwindow.h \
addressbar.h \
htmlview.h \
tabpage.h
FORMS += mainwindow.ui
QT +=network webkit webkitwidgets
#ifndef ADDRESSBAR_H
#define ADDRESSBAR_H
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QUrl>
#include <QString>
class AddressBar : public QWidget
{
Q_OBJECT
public:
explicit AddressBar(QWidget *parent = 0);
signals:
void go(const QUrl&);
void back();
void forward();
void newPage();
public slots:
void handleGoToSite();
void handleAddressChanged(const QUrl&);
private:
QLineEdit *addressEdit;
QPushButton *newButton;
QPushButton *backButton;
QPushButton *forwardButton;
QPushButton *goButton;
QHBoxLayout *layout;
};
#endif // ADDRESSBAR_H
#include "addressbar.h"
AddressBar::AddressBar(QWidget *parent) :
QWidget(parent)
{
// 1.Create widget
addressEdit = new QLineEdit;
newButton = new QPushButton("New");
backButton = new QPushButton("Back");
forwardButton = new QPushButton("Forward");
goButton = new QPushButton("Go");
// 2.Set property
// 3.Connect signal and slot
connect(goButton, SIGNAL(clicked()), this, SLOT(handleGoToSite()));
connect(addressEdit, SIGNAL(returnPressed()), this, SLOT(handleGoToSite()));
connect(backButton, SIGNAL(clicked()), this, SIGNAL(back()));
connect(forwardButton, SIGNAL(clicked()), this, SIGNAL(forward()));
connect(newButton, SIGNAL(clicked()), this, SIGNAL(newPage()));
// 4.Add to layout
layout = new QHBoxLayout;
layout->addWidget(newButton);
layout->addWidget(backButton);
layout->addWidget(forwardButton);
layout->addWidget(addressEdit);
layout->addWidget(goButton);
this->setLayout(layout);
}
void AddressBar::handleGoToSite()
{
QString address = addressEdit->text();
emit go(QUrl(address));
}
void AddressBar::handleAddressChanged(const QUrl &url)
{
addressEdit->setText(url.toString());
}
#ifndef HTMLVIEW_H
#define HTMLVIEW_H
#include <QWebView>
class HtmlView : public QWebView
{
Q_OBJECT
public:
explicit HtmlView(QWidget *parent = 0);
signals:
public slots:
void loadNewPage(const QUrl &url);
};
#endif // HTMLVIEW_H
#include "htmlview.h"
HtmlView::HtmlView(QWidget *parent) :
QWebView(parent)
{
}
void HtmlView::loadNewPage(const QUrl &url)
{
this->load(url);
}
#ifndef TABPAGE_H
#define TABPAGE_H
#include <QTabWidget>
#include <QList>
#include "htmlview.h"
class TabPage : public QTabWidget
{
Q_OBJECT
public:
explicit TabPage(QWidget *parent = 0);
~TabPage();
signals:
void urlChanged(const QUrl&);
public slots:
void handleNewTab();
void handleLoadNewPage(const QUrl&);
void handleBack();
void handleForward();
private slots:
void handleTabChanged(int);
void handleTabClosed(int);
void handleLinkClicked(const QUrl&);
private:
QList<QWebView*> viewList;
};
#endif // TABPAGE_H
#include "tabpage.h"
#include <QtDebug>
TabPage::TabPage(QWidget *parent) :
QTabWidget(parent)
{
// Set property
this->setTabsClosable(true);
// Connect built-in signal to customized one to convert index to url
connect(this, SIGNAL(currentChanged(int)), SLOT(handleTabChanged(int)));
connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabClosed(int)));
// Create new tab for home page
this->handleNewTab();
}
TabPage::~TabPage()
{
}
void TabPage::handleNewTab()
{
HtmlView *view = new HtmlView;
view->load(QUrl("qrc:/html/welcome.html"));
//view->page()->setForwardUnsupportedContent(true);
view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
// Monitor linkClicked signal
connect(view, SIGNAL(linkClicked(const QUrl&)), this, SLOT(handleLinkClicked(const QUrl&)));
// Add and activate this new tab
int index = this->addTab(view, "Welcome");
this->setCurrentIndex(index);
viewList.append(view);
}
void TabPage::handleLoadNewPage(const QUrl &url)
{
qDebug() << "loadNewPage: " << url.toString();
HtmlView *view = (HtmlView*) this->currentWidget();
view->load(url);
}
void TabPage::handleBack()
{
HtmlView *view = (HtmlView*) this->currentWidget();
view->back();
emit urlChanged(view->url());
}
void TabPage::handleForward()
{
HtmlView *view = (HtmlView*) this->currentWidget();
view->forward();
emit urlChanged(view->url());
}
void TabPage::handleTabChanged(int index)
{
if (index > viewList.length() - 1)
return;
// index is the new tab index
QWebView* view = viewList[index];
emit urlChanged(view->url());
}
void TabPage::handleTabClosed(int index)
{
if (index > viewList.length() - 1)
return;
this->removeTab(index);
QWebView* view = viewList[index];
viewList.removeAt(index);
delete view;
}
void TabPage::handleLinkClicked(const QUrl& url)
{
qDebug() << "handleLinkClicked: " << url.toString();
HtmlView *view = (HtmlView*) this->currentWidget();
view->load(url);
emit urlChanged(url);
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <QtWebKit>
#include <QMainWindow>
#include "addressbar.h"
#include "htmlview.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <QtWebKit>
#include <QMainWindow>
#include "addressbar.h"
#include "htmlview.h"
#include "tabpage.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QWebSettings* defaultSettings = QWebSettings::globalSettings();
// We use JavaScript, so set it to be enabled.
defaultSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
// Plug-ins must be set to be enabled to use plug-ins.
defaultSettings->setAttribute(QWebSettings::PluginsEnabled,true);
defaultSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,true);
defaultSettings->setObjectCacheCapacities(0, 0, 0);
// 1.Create widget
QWidget *centralWidget = new QWidget(this);
AddressBar *bar = new AddressBar;
TabPage *tab = new TabPage;
// 2.Set property
this->setCentralWidget(centralWidget);
this->setWindowTitle("My Browser v1.0");
this->resize(800, 600);
// 3.Connect widget
QObject::connect(bar, SIGNAL(newPage()),tab, SLOT(handleNewTab()));
QObject::connect(bar, SIGNAL(back()),tab, SLOT(handleBack()));
QObject::connect(bar, SIGNAL(forward()),tab, SLOT(handleForward()));
QObject::connect(bar, SIGNAL(go(QUrl)), tab, SLOT(handleLoadNewPage(QUrl)));
QObject::connect(tab, SIGNAL(urlChanged(QUrl)), bar, SLOT(handleAddressChanged(QUrl)));
// 4.Add widget to layout
QGridLayout *layout = new QGridLayout;
layout->addWidget(bar, 0, 0, 1, 10);
layout->addWidget(tab, 1, 0, 1, 10);
centralWidget->setLayout(layout);
}
#include "mainwindow.h"
#include <QApplication>
#include<QWebView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
// QWebView *view = new QWebView;
// view->load(QUrl("https://www.baidu.com/"));
// view->show();
return a.exec();
}
媒体
Header: #include <QMediaObject>
qmake: QT += multimedia
Inherits: QObject
Inherited By:
QAudioDecoder, QCamera, QMediaPlayer, and QRadioTuner