В QMessageBox, как добавить к тексту, скопированному Ctrl-C?

Используя Qt, C++ в Windows, Ctrl-C копирует выделенный текст, включающий заголовок, сообщение и т. д., из файла QMessageBox. Я добавил несколько дополнительных полей и хотел бы добавить пользовательский текст к информации, скопированной из стандартных QMessageBox из этих полей. Что мне переопределить в QMessageBox, чтобы я мог взять уже созданный текст и добавить к нему свой собственный текст?


person Mike    schedule 15.09.2015    source источник
comment
QClipboard? doc.qt.io/qt-5/qclipboard.html#details   -  person phyatt    schedule 15.09.2015


Ответы (2)


Вам нужно заново реализовать QMessageBox и все функции, которые вы хотите использовать. Вот минимальный пример:

custommessagebox.h

#include <QMessageBox>
#include <QShortcut>

class CustomMessageBox : public QMessageBox
{
    Q_OBJECT
public:
    explicit CustomMessageBox(QWidget *parent = 0);
    CustomMessageBox(Icon icon, const QString &title, const QString &text,
                StandardButtons buttons = NoButton, QWidget *parent = Q_NULLPTR,
                Qt::WindowFlags flags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
    static StandardButton information(QWidget *parent, const QString &title,
         const QString &text, StandardButtons buttons = Ok,
         StandardButton defaultButton = NoButton);

protected:
    void keyPressEvent(QKeyEvent *e);
};

custommessagebox.cpp

#include "custommessagebox.h"
#include <QClipboard>
#include <QApplication>
#include <QKeyEvent>
#include <QDialogButtonBox>

static QMessageBox::StandardButton showNewMessageBox(QWidget *parent,
    QMessageBox::Icon icon,
    const QString& title, const QString& text,
    QMessageBox::StandardButtons buttons,
    QMessageBox::StandardButton defaultButton)
{
    CustomMessageBox msgBox(icon, title, text, QMessageBox::NoButton, parent);
    QDialogButtonBox *buttonBox = msgBox.findChild<QDialogButtonBox*>();
    Q_ASSERT(buttonBox != 0);

    uint mask = QMessageBox::FirstButton;
    while (mask <= QMessageBox::LastButton) {
        uint sb = buttons & mask;
        mask <<= 1;
        if (!sb)
            continue;
        QPushButton *button = msgBox.addButton((QMessageBox::StandardButton)sb);
        // Choose the first accept role as the default
        if (msgBox.defaultButton())
            continue;
        if ((defaultButton == QMessageBox::NoButton && buttonBox->buttonRole((QAbstractButton*)button) == QDialogButtonBox::AcceptRole)
            || (defaultButton != QMessageBox::NoButton && sb == uint(defaultButton)))
            msgBox.setDefaultButton(button);
    }
    if (msgBox.exec() == -1)
        return QMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

CustomMessageBox::CustomMessageBox(QWidget *parent) : QMessageBox(parent)
{

}

CustomMessageBox::CustomMessageBox(QMessageBox::Icon icon, const QString &title, const QString &text, QMessageBox::StandardButtons buttons, QWidget *parent, Qt::WindowFlags flags)
 : QMessageBox(icon, title, text, buttons, parent, flags)
{

}

void CustomMessageBox::keyPressEvent(QKeyEvent *e)
{
    QMessageBox::keyPressEvent(e);

    if (e == QKeySequence::Copy) {
        QString separator = QString::fromLatin1("---------------------------\n");
        QString tempText = QApplication::clipboard()->text();
        tempText.append("Your custom text.\n" + separator);
        QApplication::clipboard()->setText(tempText);
    }

}

QMessageBox::StandardButton CustomMessageBox::information(QWidget *parent, const QString &title,
                               const QString& text, StandardButtons buttons,
                               StandardButton defaultButton)
{
    return showNewMessageBox(parent, Information, title, text, buttons,
                             defaultButton);
}

Использование:

void MainWindow::showCustomMessage()
{
    CustomMessageBox::information(this, "New message", "A lot of text", 0);
}

Также вам может понадобиться переопределить question(), warning(), critical() и некоторые другие функции.

person Alexander Sorokin    schedule 15.09.2015

Вы можете установить весь текст QMessageBox, выбираемый мышью, следующим образом:

QMessageBox mb;
mb.setTextInteractionFlags(Qt::TextSelectableByMouse);

QMessageBox::setTextInteractionFlags(флаги Qt::TextInteractionFlags);

person fbucek    schedule 15.09.2015
comment
Не совсем то, о чем я спрашивал, но само по себе очень полезно, поэтому за него проголосовали. Спасибо. - person Mike; 15.09.2015
comment
После того, как я отправил это, я понял, что вы спрашивали о чем-то другом. Меня немного смутил ваш вопрос :) - person fbucek; 15.09.2015