Balint Ablonczy, who followed the election for the magazine, said that the opposition had grown used to a long string of Fidesz victories in the past decade, and that this victory was a cause for optimism for it.

Hodmezovasarhely in many ways stands for both the successes and failures of nearly eight years of governments led by Mr. Orban. The city, widely seen as loyal to prime minister, has benefited under the tutelage of Mr. Lazar, the chief of staff and a former mayor, who continued to sit in on town hall meetings. Its infrastructure was improved and planning started on a light-rail line to connect Hodmezovasarhely to the nearby city of Szeged, where many residents commute to work.

But the local Fidesz leadership faced accusations of cronyism, often in the distribution of European Union funding, that, as in the rest of the country, have grown louder.

Earlier this year the European Anti-Fraud Office announced that it was investigating almost three dozen public lighting projects in Hungary run by a company once controlled by Mr. Orban’s son-in-law. The first such project was completed in Hodmezovasarhely, and news reports, which have suggested that the project was a pilot for later ones, described some of the practices involved as comparable to those used by organized crime.

Such accusations, which the leadership denied, appeared to have helped the winning candidate, who mobilized new voters to go to the ballots.

“Corruption is like slow poison,” said Robert Laszlo, a researcher who specializes in elections at Political Capital, an independent think tank in Budapest, the capital. “People go along with it for a while, but there is a level beyond which people have had enough, when it’s really obvious.”

Winning in a place like Hodmezovasarhely could be a catalyst for the opposition. Although the restructuring of Hungary’s election system has helped Mr. Orban remain in power, Mr. Laszlo pointed out that Fidesz and the Christian Democratic People’s Party, its coalition partner, received a smaller share of the vote than the opposition in the last general election in 2014.