首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

QT学习札记-36.QTableWidget根据表格自动调整列宽度

2012-08-28 
QT学习笔记-36.QTableWidget根据表格自动调整列宽度return model-setData(index, state, Qt::CheckStateR

QT学习笔记-36.QTableWidget根据表格自动调整列宽度


        return model->setData(index, state, Qt::CheckStateRole);
    }
    void drawFocus(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect) const
    {
        QItemDelegate::drawFocus(painter, option, option.rect);
    }
};

static int ROWS = 3;
static int COLS = 3;

class Table : public QTableWidget
{
public:
    Table(QWidget *parent = 0)
        : QTableWidget(ROWS, COLS, parent)
    {
        setItemDelegate(new ItemDelegate(this));
        QTableWidgetItem *item = 0;
        for(int i=0; i<rowCount(); ++i)
        {
            for(int j=0; j<columnCount(); ++j)
            {
                setItem(i, j, item = new QTableWidgetItem);
                QTableViewItem;
                item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
                item->setCheckState((i+j) % 2 == 0 ? Qt::Checked : Qt::Unchecked);
            }
        }
    }
};

int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    Table w;
    w.show();
    return a.exec();
}
posted @ 2011-11-26 11:25 ccsdu2009 阅读(264) | 评论 (0) | 编辑 收藏 QT学习笔记-31.QTableView只显示横格,不显示点击虚框的方法重新风格项代理QStyledItemDelegat

class QLineDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    QLineDelegate(QTableView* tableView);
protected:
    void paint(QPainter* painter,const QStyleOptionViewItem& option,const QModelIndex& index) const;
private:
    QPen         pen;
    QTableView*  view;
};
#include <QPainter>
#include "QLineDelegate.h"

QLineDelegate::QLineDelegate(QTableView* tableView)
{
    int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4());
    QColor gridColor = static_cast<QRgb>(gridHint);
    pen = QPen(gridColor, 0, tableView->gridStyle());
    view = tableView;
}

void QLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,const QModelIndex& index)const
{
    QStyleOptionViewItem itemOption(option);
    if(itemOption.state & QStyle::State_HasFocus)
        itemOption.state = itemOption.state ^ QStyle::State_HasFocus;
    QStyledItemDelegate::paint(painter,itemOption,index);
    QPen oldPen = painter->pen();
    painter->setPen(pen);
    //painter->drawLine(option.rect.topRight(),option.rect.bottomRight());
    painter->drawLine(itemOption.rect.bottomLeft(),itemOption.rect.bottomRight());
    painter->setPen(oldPen);
}
posted @ 2011-11-25 20:22 ccsdu2009 阅读(228) | 评论 (0) | 编辑 收藏 QT学习笔记-30.QTableView只显示横格的方式默认QTableView是显示网状格子的,如果不显示网格则可以调用setShowGrid(false);来实现。但是如果只想显示横线则有点复杂了。具体代码如下:
#include <QApplication>

#include <QTableWidget>
#include <QPainter>
#include <QStyledItemDelegate>
#include <QHeaderView>
class QLineDelegate : public QStyledItemDelegate
{
public:
 QLineDelegate(QTableView* tableView);
protected:
 void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
private:
 QPen pen;
 QTableView* view;
};
QLineDelegate::QLineDelegate(QTableView* tableView)
{
 int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4());
 QColor gridColor = static_cast<QRgb>(gridHint);
 pen = QPen(gridColor, 0, tableView->gridStyle());
 view = tableView;
}
void QLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,const QModelIndex& index)const
{
 QStyledItemDelegate::paint(painter, option, index);
 QPen oldPen = painter->pen();
 painter->setPen(pen);
 //painter->drawLine(option.rect.topRight(), option.rect.bottomRight());
 painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());
 painter->setPen(oldPen);
}
class QLineTableWidget:public QTableWidget
{
public:
 QLineTableWidget();
};
QLineTableWidget::QLineTableWidget()
{
 setStyleSheet("QTableView::Item{selection-background-color:#101020}");
 setStyleSheet("QTableView::Item{background-color:#F0F0F0}");
 verticalHeader()->setVisible(false);
 horizontalHeader()->setVisible(true);
 setSelectionBehavior(QAbstractItemView::SelectRows);
 setSelectionMode(QAbstractItemView::SingleSelection);
 setEditTriggers(QTableView::NoEditTriggers);
 setColumnCount(3);
 setRowCount(4);
 setShowGrid(false);
 setItemDelegate(new QLineDelegate(this));
 setCurrentCell(-1,-1);
}
int main(int argc,char **argv)
{
 QApplication a(argc,argv);
 QLineTableWidget widget;
 widget.show();
 return a.exec();
}
posted @ 2011-11-22 22:23 ccsdu2009 阅读(1253) | 评论 (0) | 编辑 收藏 QT学习笔记-30.自写的QT插件系统#ifndef QPLUGIN_SYSTEM_H
#define QPLUGIN_SYSTEM_H
#include <QObject>
#include <QVector>
#include <QPluginLoader>
#include <QDir>

template<class T>
class QPluginSystem
{
public:
    void setup();
    int  getAddonCnt(){return addons.size();}
    T*   getAddonByIndex(int index){return addons.at(index);}    
private:
    QVector<QPluginLoader*> loaders;
    QVector<T*>             addons;
};

template<class T>
void QPluginSystem<T>::setup()
{
    QString path = QDir::currentPath();
    path += QDir::separator();
    path += "addons";
    QDir pluginsDir(path);

    foreach(QString fileName,pluginsDir.entryList(QDir::Files))
    {   
        bool autodel = false;
        QPluginLoader* pluginLoader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = pluginLoader->instance();
        if(plugin)
        {
            T *interface = qobject_cast<T*>(plugin);
            if(interface)
            {
                addons.push_back(interface);
                loaders.push_back(pluginLoader);
                autodel = true;
            }
        }

        if(autodel == false)
            delete pluginLoader;
    }
}

#endif
其中T是插件对象,需要继承QObject
另外虽然我没试过,但是我感觉增加QPluginLoader链表是很有必要的
posted @ 2011-11-17 22:11 ccsdu2009 阅读(121) | 评论 (0) | 编辑 收藏 QT学习笔记-29.使用QT HTTP下载网络文件QT附带的例子比较好:
class HttpWindow : public QDialog
{
    Q_OBJECT
public:
    HttpWindow(QWidget *parent = 0);

    void startRequest(QUrl url);
private slots:
    void downloadFile();
    void cancelDownload();
    void httpFinished();
    void httpReadyRead();
    void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
    void enableDownloadButton();
    void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
private:
    QLabel *statusLabel;
    QLabel *urlLabel;
    QLineEdit *urlLineEdit;
    QProgressDialog *progressDialog;
    QPushButton *downloadButton;
    QPushButton *quitButton;
    QDialogButtonBox *buttonBox;

    QUrl url;
    QNetworkAccessManager qnam;
    QNetworkReply *reply;
    QFile *file;
    int httpGetId;
    bool httpRequestAborted;
};其中槽有:
1.开始下载
2.取消下载
3.预备下载
4.下载完成
5.进度回调


实现为:
void HttpWindow::startRequest(QUrl url)
{
    reply = qnam.get(QNetworkRequest(url));
    connect(reply, SIGNAL(finished()),
            this, SLOT(httpFinished()));
    connect(reply, SIGNAL(readyRead()),
            this, SLOT(httpReadyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
            this, SLOT(updateDataReadProgress(qint64,qint64)));
}该函数主要针对给定url绑定事件
void HttpWindow::downloadFile()
{
    url = urlLineEdit->text();

    QFileInfo fileInfo(url.path());
    QString fileName = fileInfo.fileName();
    fileName = "downloadfile.dat";
    if(fileName.isEmpty())
        fileName = "index.html";

    if(QFile::exists(fileName)) {
        if (QMessageBox::question(this, tr("HTTP"), 
                                  tr("There already exists a file called %1 in "
                                     "the current directory. Overwrite?").arg(fileName),
                                  QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
            == QMessageBox::No)
            return;
        QFile::remove(fileName);
    }

    file = new QFile(fileName);
    if (!file->open(QIODevice::WriteOnly)) {
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Unable to save the file %1: %2.")
                                 .arg(fileName).arg(file->errorString()));
        delete file;
        file = 0;
        return;
    }

    progressDialog->setWindowTitle(tr("HTTP"));
    progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
    downloadButton->setEnabled(false);

    // schedule the request
    httpRequestAborted = false;
    startRequest(url);
}
当点击下载的时候,会执行该函数
获取url链接,生成本地文件,...
void HttpWindow::cancelDownload()
{
    statusLabel->setText(tr("Download canceled."));
    httpRequestAborted = true;
    reply->abort();
    downloadButton->setEnabled(true);
}终止下载,主要函数是reply->abort();
void HttpWindow::httpFinished()
{
    if (httpRequestAborted) {
        if (file) {
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        reply->deleteLater();
        progressDialog->hide();
        return;
    }

    progressDialog->hide();
    file->flush();
    file->close();


    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (reply->error()) {
        file->remove();
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Download failed: %1.")
                                 .arg(reply->errorString()));
        downloadButton->setEnabled(true);
    } else if (!redirectionTarget.isNull()) {        
        QUrl newUrl = url.resolved(redirectionTarget.toUrl());
        if (QMessageBox::question(this, tr("HTTP"),
                                  tr("Redirect to %1 ?").arg(newUrl.toString()),
                                  QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
            url = newUrl;
            reply->deleteLater();
            file->open(QIODevice::WriteOnly);
            file->resize(0);
            startRequest(url);
            return;
        }
    } else {
        QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
        statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
        downloadButton->setEnabled(true);
    }

    reply->deleteLater();
    reply = 0;
    delete file;
    file = 0;
}  下载结束动作
void HttpWindow::httpReadyRead()
{
    // this slot gets called every time the QNetworkReply has new data.
    // We read all of its new data and write it into the file.
    // That way we use less RAM than when reading it at the finished()
    // signal of the QNetworkReply
    if (file)
        file->write(reply->readAll());
}写文件回调
void HttpWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
    if (httpRequestAborted)
        return;

    progressDialog->setMaximum(totalBytes);
    progressDialog->setValue(bytesRead);
}

热点排行