返回

Qwidget实现文本拖放

发布时间:2022-09-16 10:50:22 341
# html
//.h文件
class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = 0);
~MainWindow();

protected:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);

private:
bool readFile(const QString &fileName);
QTextEdit *textEdit;
};
//.cpp文件
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);

textEdit->setAcceptDrops(false);
setAcceptDrops(true);

setWindowTitle(tr("Text Editor"));
}

MainWindow::~MainWindow()
{
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("text/uri-list")) {
event->acceptProposedAction();
}
}

void MainWindow::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 - %2").arg(fileName, tr("Drag File")));
}
}

bool MainWindow::readFile(const QString &fileName)
{
bool r = false;
QFile file(fileName);
QTextStream in(&file);
QString content;
if(file.open(QIODevice::ReadOnly)) {
in >> content;
r = true;
}
textEdit->setText(content);
return r;
}
//
创建显示
MainWindow *w=cqltbe_new(MainWindow);
w->show();

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线