我是Qt的新手,我正在尝试构建一个简单的文本编辑器。我想要一个搜索功能,目前它只是我文本编辑器主窗口顶部的静态工具栏。我想要的是一种弹出式工具栏,就像在Chrome或Firefox中一样,只要我选择" Find"从菜单中按或按Ctrl + F,工具栏出现,一旦我按下它,它就会消失。
我也有一些焦点问题atm,如果我按下Ctrl + F,我的QLineEdit
上没有闪烁的光标,我不知道为什么。
欢迎任何提示!提前谢谢!
我的mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QShortcut>
#include <QFile>
#include <QDebug>
#include"searchdialog.h"
#include <QToolBar>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void open_search_window();
private:
Ui::MainWindow *ui;
QString m_filename;
SearchDialog *m_dialog;
QToolBar *m_toolbar;
};
#endif // MAINWINDOW_H
然后,mainwindow.cpp
#include "mainwindow.h"
#include "searchdialog.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_dialog = new SearchDialog();
m_dialog->show();
m_toolbar = new QToolBar(this);
m_toolbar->addWidget(m_dialog);
this->addToolBar(m_toolbar);
connect(ui->actionquit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->actionFind, SIGNAL(triggered()), this, SLOT(open_search_window()));
new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this, SLOT(open_search_window()));
}
MainWindow::~MainWindow()
{
delete ui;
delete m_dialog;
}
void MainWindow::open_search_window()
{
m_dialog->show();
}
我自己定义的Searchdialog
类:
#ifndef SEARCHDIALOG_H
#define SEARCHDIALOG_H
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
#include <QShortcut>
class SearchDialog : public QWidget {
Q_OBJECT
public:
explicit SearchDialog(QWidget* parent = 0);
QLabel* m_label;
public slots:
void find_next();
signals:
void new_search(QString search_string);
private:
QLineEdit* m_searchInput;
QPushButton* m_cancel;
QPushButton* m_findNext;
};
#endif // SEARCHDIALOG_H
searchdialog.cpp
#include "searchdialog.h"
SearchDialog::SearchDialog(QWidget* parent)
: QWidget(parent)
{
this->setWindowTitle("Find stuff...");
m_label = new QLabel(tr("Find what:"));
m_searchInput = new QLineEdit;
m_findNext = new QPushButton(tr("&Find"));
m_cancel = new QPushButton(tr("&Close"));
connect(m_cancel, SIGNAL(clicked()), this, SLOT(close()));
connect(m_findNext,SIGNAL(clicked()),this, SLOT(find_next()));
new QShortcut(QKeySequence(Qt::Key_Enter), this, SLOT(find_next()));
QHBoxLayout* findLayout = new QHBoxLayout();
findLayout->addWidget(m_label);
findLayout->addWidget(m_searchInput);
QHBoxLayout* buttonsLayout = new QHBoxLayout();
buttonsLayout->addWidget(m_findNext);
buttonsLayout->addWidget(m_cancel);
QVBoxLayout* windowLayout = new QVBoxLayout();
windowLayout->addLayout(findLayout);
windowLayout->addLayout(buttonsLayout);
this->setLayout(windowLayout);
}
void SearchDialog::find_next()
{
if (!m_searchInput->text().isEmpty()) {
QString searchString = m_searchInput->text();
emit new_search(searchString);
}
}