是否可以锁定 QListWidget 中的项目,所以当我按下例如:一个按钮时,该项目保持选中状态?我试图查找它,但我失败了
问问题
72 次
1 回答
1
我真的希望你能给我一个例子,因为我只是一个初学者
我可以。开始了:
testQListWidgetLockSelection.cc
:
#include <set>
#include <QtWidgets>
class ListWidget: public QListWidget {
public:
using QListWidget::QListWidget;
virtual ~ListWidget() = default;
void lockSelection(bool lock);
virtual void selectionChanged(
const QItemSelection &selected,
const QItemSelection &deselected) override;
private:
bool _lockSel = false;
std::set<int> _selLocked;
bool _lockResel = false;
struct LockGuard {
bool &lock;
LockGuard(bool &lock): lock(lock) { lock = true; }
~LockGuard() { lock = false; }
};
};
void ListWidget::lockSelection(bool lock)
{
_lockSel = lock;
if (_lockSel) {
// store selected indices
for (const QModelIndex &qMI : selectedIndexes()) _selLocked.insert(qMI.row());
} else _selLocked.clear();
}
void ListWidget::selectionChanged(
const QItemSelection& selected, const QItemSelection& deselected)
{
if (_lockSel && !_lockResel) {
const LockGuard lock(_lockResel);
QItemSelection reselect;
for (int row : _selLocked) {
const QModelIndex qMI = model()->index(row, 0);
reselect.select(qMI, qMI);
}
selectionModel()->select(reselect, QItemSelectionModel::Select);
}
}
void populate(QListWidget& qLstView)
{
for (int i = 1; i <= 20; ++i) {
qLstView.addItem(QString("Item %1").arg(i));
}
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
QWidget qWinMain;
qWinMain.resize(640, 480);
qWinMain.setWindowTitle("Lock Selection Demo");
QVBoxLayout qVBox;
QCheckBox qTglLockSel("Lock Selection");
qVBox.addWidget(&qTglLockSel, false);
ListWidget qLstView;
qLstView.setSelectionMode(ListWidget::ExtendedSelection);
qVBox.addWidget(&qLstView, true);
qWinMain.setLayout(&qVBox);
qWinMain.show();
// install signal handlers
QObject::connect(&qTglLockSel, &QCheckBox::toggled,
&qLstView, &ListWidget::lockSelection);
// fill GUI with sample data
populate(qLstView);
// runtime loop
return app.exec();
}
演示:
笔记:
该示例有一个弱点:它没有考虑在选择被锁定后可以插入或删除项目。
为了增强这一点,还必须重写成员函数rowsInserted()和rowsAboutToBeRemoved()以ListWidget::_selLocked
分别更正索引。
于 2021-02-05T11:55:04.010 回答