Files
change_code/main.cpp
T

106 lines
3.4 KiB
C++

#include "src/mainwindow/mainwindow.h"
#include "ElaApplication.h"
#include "src/utils/configmanager.h"
#include <QApplication>
#include <QIcon>
#include <QCoreApplication>
#include <QEvent>
#include <QKeyEvent>
#include <QClipboard>
#include <QKeySequence>
#include <QLabel>
#include <QAbstractItemView>
#include <QModelIndex>
#include <algorithm>
// 全局文字可复制过滤器:
// 1) 所有 QLabel(含 ElaText)文字可用鼠标选中并复制;
// 2) 表格/树(QAbstractItemView)选中的单元格支持 Ctrl+C 复制,制表符分隔列、换行分隔行。
class TextSelectableFilter : public QObject
{
public:
using QObject::QObject;
protected:
bool eventFilter(QObject *watched, QEvent *event) override
{
if (event->type() == QEvent::Polish) {
if (QLabel *label = qobject_cast<QLabel *>(watched)) {
// 跳过用作图标按钮的 QLabel(有 pixmap 无文本),
// 否则会被强制设为竖线(IBeamCursor),影响点击类图标控件
if (label->pixmap().isNull()) {
label->setTextInteractionFlags(label->textInteractionFlags()
| Qt::TextSelectableByMouse);
label->setCursor(Qt::IBeamCursor);
}
}
} else if (event->type() == QEvent::KeyPress) {
if (auto *view = qobject_cast<QAbstractItemView *>(watched)) {
auto *ke = static_cast<QKeyEvent *>(event);
if (ke->matches(QKeySequence::Copy)) {
return copySelectedCells(view);
}
}
}
return QObject::eventFilter(watched, event);
}
private:
static bool copySelectedCells(QAbstractItemView *view)
{
if (!view->selectionModel()) {
return false;
}
QModelIndexList idxs = view->selectionModel()->selectedIndexes();
if (idxs.isEmpty()) {
return false;
}
// 按行、列排序,保证复制顺序与显示一致
std::sort(idxs.begin(), idxs.end(),
[](const QModelIndex &a, const QModelIndex &b) {
if (a.row() != b.row()) {
return a.row() < b.row();
}
return a.column() < b.column();
});
QString text;
int lastRow = -1;
for (const QModelIndex &idx : idxs) {
if (idx.row() != lastRow) {
if (lastRow != -1) {
text += QLatin1Char('\n');
}
lastRow = idx.row();
} else {
text += QLatin1Char('\t');
}
text += idx.data(Qt::DisplayRole).toString();
}
if (!text.isEmpty()) {
QApplication::clipboard()->setText(text);
return true; // 已处理,消费该事件
}
return false;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setWindowIcon(QIcon(":resources/images/ChangeCode.png"));
// 安装全局过滤器:所有页面文字 / 表格树单元格允许用户复制
TextSelectableFilter textSelectableFilter;
a.installEventFilter(&textSelectableFilter);
eApp->init();
QString basePath = QCoreApplication::applicationDirPath();
ConfigManager::instance()->loadConfig(basePath);
MainWindow w;
w.showMaximized();
return a.exec();
}