I'm attempting to create a QLineEdit
element whose text will be automatically copied to the clipboard when clicked.
I've created the following eventFilter
to capture the click event and installed it on the applicable elements:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
{
qDebug("TEST");
return true;
}
else
{
return false;
}
}
What would be the best way from here to gather the data I need from the object to pass to the clipboard function?
Use the QClipboard
class. You can get your application's clipboard using qApp->clipboard()
and then set the text from the QLineEdit
:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
{
auto watched_as_lineEdit = qobject_cast<QLineEdit*>(watched);
if (watched_as_lineEdit != nullptr) {
qApp->clipboard()->setText(watched_as_lineEdit->text());
return true;
}
}
return QMainWindow::eventFilter(watched, event); // change for actual parent class if different from QMainWindow
}