Qt 小例子学习13 - PopupTableView
#ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include <QDialog>
#include <QEvent>
#include <QHeaderView>
#include <QLabel>
#include <QMouseEvent>
#include <QTableView>
#include <QVBoxLayout>
class TableView : public QTableView
{
Q_OBJECT
QDialog* popup;
QLabel* popupLabel;
public:
TableView(QWidget* parent = Q_NULLPTR) : QTableView(parent)
{
viewport()->installEventFilter(this);
setMouseTracking(true);
popup = new QDialog(this, Qt::Popup | Qt::ToolTip);
QVBoxLayout* layout = new QVBoxLayout;
popupLabel = new QLabel(popup);
popupLabel->setWordWrap(true);
layout->addWidget(popupLabel);
popupLabel->setTextFormat(Qt::RichText);
// popupLabel->setOpenExternalLinks(true);
popup->setLayout(layout);
popup->installEventFilter(this);
}
bool eventFilter(QObject* watched, QEvent* event)
{
if(viewport() == watched)
{
if(event->type() == QEvent::MouseMove)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
QModelIndex index = indexAt(mouseEvent->pos());
if(index.isValid())
{
showPopup(index);
}
else
{
popup->hide();
}
}
else if(event->type() == QEvent::Leave)
{
popup->hide();
}
}
else if(popup == watched)
{
if(event->type() == QEvent::Leave)
{
popup->hide();
}
}
return QTableView::eventFilter(watched, event);
}
private:
void showPopup(const QModelIndex& index) const
{
if(index.column() == 1)
{
QRect r = visualRect(index);
popup->move(viewport()->mapToGlobal(r.bottomLeft()));
popup->setFixedSize(100, popup->heightForWidth(100));
popupLabel->setText(index.data(Qt::DisplayRole).toString());
popup->adjustSize();
popup->show();
}
else
{
popup->hide();
}
}
};
#endif // TABLEVIEW_H
#include "tableview.h"
#include <QApplication>
#include <QStandardItemModel>
const QString text =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
"Lorem Ipsum has been the industry's standard dummy text ever since the "
"1500s,"
" when an unknown printer took a galley of type and scrambled it to make a "
"type specimen book."
"It has survived not only five centuries, but also the leap into "
"electronic typesetting,"
" remaining essentially unchanged."
"It was popularised in the 1960s with the release of Letraset sheets "
"containing Lorem Ipsum passages,"
"and more recently with desktop publishing software like Aldus PageMaker "
"including versions of Lorem Ipsum.";
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
TableView w;
QStandardItemModel model(10, 2);
for(int row = 0; row < model.rowCount(); row++)
{
for(int col = 0; col < model.columnCount(); col++)
{
QModelIndex index = model.index(row, col, QModelIndex());
if(col == 1)
{
model.setData(index, text);
}
else
{
model.setData(index, QString("%1, %2").arg(row).arg(col));
}
}
}
w.setModel(&model);
w.show();
return a.exec();
}