从QTreeWidget覆盖复制文本操作

时间:2018-11-07 14:17:18

标签: c++ qt clipboard copy-paste

我有一个reshape,在这里我将从add_child覆盖复制文本(ctrl + c)。

默认行为是从所选列中复制#include <iostream> #include <string> #include <map> #include <vector> using namespace std; void add_family(map<string, vector<string>> &family, const string &name) { if (family.find(name) == family.end()) { family.insert({name, vector<string>()}); } else { cerr << "Error: Already has family <" << name << ">" << endl; } } void add_child(map<string, vector<string>> &family, const string &family_name, const string &child_name) { auto it = family.find(family_name); if (it != family.cend()) { it->second.push_back(child_name); } else { cerr << "Error: No family <" << family_name << "> for child <" << child_name << ">" << std::endl; } } int main(int argc, char const *argv[]) { map<string, vector<string>> family; add_family(family, "Family1"); add_family(family, "Family2"); add_family(family, "Family1"); // Error add_child(family, "Family1", "Name1"); add_child(family, "Family1", "Name2"); add_child(family, "Family1", "Name3"); add_child(family, "Family1", "Name3"); //will create duplicate add_child(family, "Family2", "Name1"); add_child(family, "Family2", "Name2"); add_child(family, "Family2", "Name3"); add_child(family, "Family3", "Name1"); // Error for (const auto &f : family) for (const auto &name : f.second) cout << f.first << " " << name << endl; return 0; } ,但是我想用我在后台获得的更多信息来更新值。

是否有一种本机的方法而不用Error: Already has family <Family1> Error: No family <Family3> for child <Name1> Family1 Name1 Family1 Name2 Family1 Name3 Family1 Name3 Family2 Name1 Family2 Name2 Family2 Name3 捕获QTreeWidget

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法将自己的内容存储在剪贴板中,而不覆盖QWidget::keyPressEvent()

// Assuming tree widget already exists.
auto shortcut = new QShortcut(QKeySequence("Ctrl+C"), treeWidget);
QObject::connect(shortcut, &QShortcut::activated, [treeWidget] () {
    auto selected = treeWidget->selectedItems();
    // Get only first selected item's text.
    if (selected.size() > 0)
    {
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(QString("Custom clipboard text: %1").arg(selected.at(0)->text(0)));
    }
});

在代码中,我使用QShortcut处理Ctrl+C键序列并将选定的树小部件项目的文本(自定义)存储到剪贴板中。