0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

QTableWidget::currentItemChanged をキャンセルし セレクションを戻す

Posted at

はじめに

Qt6.2 の QTableWidget::currentItemChanged に接続した Functor でキャンセルさせ セレクションを戻す方法に迷走
力技的なところはありますが共有

確認環境

  • Windows 10 x64
  • Qt 6.2

概要

QTableWidget::currentItemChanged と接続した Functor 内で previous を選択してもダメなようなので Functor から抜けた処理で選択すれば良いとのではと考察
その結果 QTimer::singleShot と接続した Functor 内で選択処理すれば実現できることを確認
⇒タイマーイベントで選択処理をキューイング

サンプルコード

#include <QtWidgets>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QWidget w;
    QTableWidget *tbl = new QTableWidget(&w);
    QGridLayout *l = new QGridLayout;

    w.setLayout(l);
    l->addWidget(tbl, 0, 0);
    QObject::connect(&app, &QApplication::lastWindowClosed, &app, &QApplication::quit);
	tbl->setColumnCount(1);
	tbl->setHorizontalHeaderLabels({("Name")});
	tbl->setSelectionBehavior(tbl->SelectRows);
	tbl->setSelectionMode(tbl->SingleSelection);
	tbl->setEditTriggers(tbl->NoEditTriggers);
    for (int row = 0; row < 5; ++row) {
        tbl->setRowCount(row + 1);
        tbl->setItem(row, 0, new QTableWidgetItem(QString::number(row)));
    }
    QObject::connect(tbl, &QTableWidget::currentItemChanged, [&](QTableWidgetItem *current, QTableWidgetItem *previous) {
		if (! previous) {
            return;
        }
        if (QMessageBox::Yes != QMessageBox::question(&w, "Confirm", "Do you want to switch?")) {
            /*
             * QTableWidget::currentItemChanged の後に選択処理を入れてあげればよさげ
             */
            QTimer::singleShot(1, [previous]() {
                QTableWidget *tbl = previous->tableWidget();
                QSignalBlocker sb(tbl); // これを忘れるとループ

                tbl->setCurrentItem(previous);
            });
            return;
        }
        // TODO: current に対して必要な処理
        current;
	});
    w.show();
    return app.exec();
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?